我有一个包含多个ComboBoxes
的WPF应用程序。某些组合框的ItemsSource
绑定到对象列表。我想将每个组合框的text属性绑定到MyObject
的某个属性。每次用户选择MyListView
中的某一行时,我都会更新MyObject
的属性,并且我还希望更新组合框的文本属性。
这是其中一个组合框的XAML:
<StackPanel Orientation="Vertical" x:Name="StackPanel_MyStackPanel">
<ComboBox x:Name="comboBox_MyComboBox"
IsEditable="True"
ItemsSource="{Binding}"
Text="{Binding Path=MyProperty}" />
</StackPanel>
在背后的代码中:
MyObject myObject = new MyObject();
// On the selection changed event handler of the MyListView,
// I update the MyProperty of the myObject.
this.StackPanel_MyStackPanel.DataContext = myObject;
MyObject
的定义:
public class MyObject
{
private string _MyProperty;
public string MyProperty
{
get { return _MyProperty; }
set { _MyProperty = value; }
}
}
这不起作用....我不知道为什么。
答案 0 :(得分:1)
您的数据类需要实现INotifyPropertyChanged:
public class MyObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _MyProperty;
public string MyProperty
{
get { return _MyProperty;}
set
{
_MyProperty = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("MyProperty"));
}
}
}
}
答案 1 :(得分:0)
对我而言,它正在发挥作用..
btw,ItemsSource用于组合框中的项目,你不需要在这里设置
我添加了一个用于测试它的按钮......这是我的代码隐藏:
MyObject myObject = new MyObject();
/// <summary>
/// Initializes a new instance of the <see cref="MainView"/> class.
/// </summary>
public MainView()
{
InitializeComponent();
//On the selection changed event handler of the MyListView , I update the
//MyProperty of the myObject.
this.StackPanel_MyStackPanel.DataContext = myObject;
}
private void test_Click(object sender, System.Windows.RoutedEventArgs e)
{
MessageBox.Show(myObject.MyProperty);
}
我的XAML:
<StackPanel x:Name="StackPanel_MyStackPanel"
Width="Auto"
Height="Auto"
Orientation="Vertical">
<ComboBox x:Name="comboBox_MyComboBox"
IsEditable="True"
Text="{Binding Path=MyProperty}" />
<Button Name="test" Click="test_Click" Content="Show it" />
</StackPanel>
我执行了MyObject
,但将您的本地变量重命名为_MyProperty
- 它是MyPropety