Reputation: 8474
How to bind to static property programmatically? What can I use in C# to make
{Binding Source={x:Static local:MyClass.StaticProperty}}
Update: is it possible to do OneWayToSource binding? I understand that TwoWay is not possible because there are no update events on static objects (at least in .NET 4). I cannot instantiate object because it is static.
Upvotes: 5
Views: 4857
Reputation: 19296
OneWay binding
Let's assume that you have class Country
with static property Name
.
public class Country
{
public static string Name { get; set; }
}
And now you want binding property Name
to TextProperty
of TextBlock
.
Binding binding = new Binding();
binding.Source = Country.Name;
this.tbCountry.SetBinding(TextBlock.TextProperty, binding);
Update: TwoWay binding
Country
class looks like this:
public static class Country
{
private static string _name;
public static string Name
{
get { return _name; }
set
{
_name = value;
Console.WriteLine(value); /* test */
}
}
}
And now we want binding this property Name
to TextBox
, so:
Binding binding = new Binding();
binding.Source = typeof(Country);
binding.Path = new PropertyPath(typeof(Country).GetProperty("Name"));
binding.Mode = BindingMode.TwoWay;
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
this.tbCountry.SetBinding(TextBox.TextProperty, binding);
If you want update target you must use BindingExpression
and function UpdateTarget
:
Country.Name = "Poland";
BindingExpression be = BindingOperations.GetBindingExpression(this.tbCountry, TextBox.TextProperty);
be.UpdateTarget();
Upvotes: 8
Reputation: 54781
You could always write a non-static class to provide access to the static one.
Static class:
namespace SO.Weston.WpfStaticPropertyBinding
{
public static class TheStaticClass
{
public static string TheStaticProperty { get; set; }
}
}
Non-static class to provide access to static properties.
namespace SO.Weston.WpfStaticPropertyBinding
{
public sealed class StaticAccessClass
{
public string TheStaticProperty
{
get { return TheStaticClass.TheStaticProperty; }
}
}
}
Binding is then simple:
<Window x:Class="SO.Weston.WpfStaticPropertyBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SO.Weston.WpfStaticPropertyBinding"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:StaticAccessClass x:Key="StaticAccessClassRes"/>
</Window.Resources>
<Grid>
<TextBlock Text="{Binding Path=TheStaticProperty, Source={StaticResource ResourceKey=StaticAccessClassRes}}" />
</Grid>
</Window>
Upvotes: 0