如何在后面的 wpf 代码中绑定静态变量?
How can I bind static variable in wpf code behind?
我有静态class'MappingService'.
public class MappingService : INotifyPropertyChanged
{
static readonly MappingService _Instance = new MappingService();
public static MappingService Instance
{
get { return _Instance; }
}
public Efficiency Source { get; set; }
}
并在后面的代码中创建 ComboBox。
我想在后面的代码中绑定 ItemsSource MappingService.Instance.Source。
comboBox.SetBinding(ItemsControl.ItemsSourceProperty, new Binding("MappingService.Instance.Source") { Mode = BindingMode.TwoWay });
但我无法访问 MappingService.Instance.Source。
请帮助我。
谢谢。
这是一种简单的方法 it.There 可能是比这更好的选择,具体取决于您的设计。试试这个
public class MappingService : INotifyPropertyChanged
{
static readonly MappingService _Instance = new MappingService();
public static MappingService Instance
{
get { return _Instance; }
}
public MappingService BindingObject
{
get { MappingService._Instance; }
}
public Efficiency Source { get; set; }
}
还有你的 xaml 代码。
comboBox.SetBinding(ItemsControl.ItemsSourceProperty, new Binding("BindingObject.Source") { Mode = BindingMode.TwoWay });
您只需在实例引用中添加静态引用。
绑定方法如下:
var propertyPath = new PropertyPath("Source");
var binding = new System.Windows.Data.Binding
{
Path = propertyPath,
Mode = BindingMode.TwoWay,
Source = MappingService.Instance
};
BindingOperations.SetBinding(
comboBox,
System.Windows.Controls.ItemsControl.ItemsSourceProperty,
binding);
我有静态class'MappingService'.
public class MappingService : INotifyPropertyChanged
{
static readonly MappingService _Instance = new MappingService();
public static MappingService Instance
{
get { return _Instance; }
}
public Efficiency Source { get; set; }
}
并在后面的代码中创建 ComboBox。
我想在后面的代码中绑定 ItemsSource MappingService.Instance.Source。
comboBox.SetBinding(ItemsControl.ItemsSourceProperty, new Binding("MappingService.Instance.Source") { Mode = BindingMode.TwoWay });
但我无法访问 MappingService.Instance.Source。
请帮助我。 谢谢。
这是一种简单的方法 it.There 可能是比这更好的选择,具体取决于您的设计。试试这个
public class MappingService : INotifyPropertyChanged
{
static readonly MappingService _Instance = new MappingService();
public static MappingService Instance
{
get { return _Instance; }
}
public MappingService BindingObject
{
get { MappingService._Instance; }
}
public Efficiency Source { get; set; }
}
还有你的 xaml 代码。
comboBox.SetBinding(ItemsControl.ItemsSourceProperty, new Binding("BindingObject.Source") { Mode = BindingMode.TwoWay });
您只需在实例引用中添加静态引用。
绑定方法如下:
var propertyPath = new PropertyPath("Source");
var binding = new System.Windows.Data.Binding
{
Path = propertyPath,
Mode = BindingMode.TwoWay,
Source = MappingService.Instance
};
BindingOperations.SetBinding(
comboBox,
System.Windows.Controls.ItemsControl.ItemsSourceProperty,
binding);