绑定ComboBox中的文本属性无法工作

3
我有一个包含几个ComboBox的WPF应用程序。其中一些comboboxes的ItemsSource绑定到对象列表。我想将每个combobox的文本属性绑定到MyObject的某个属性。每次用户选择MyListView中的某行时,我都会更新MyObject的属性,并且我希望comboboxes的文本属性也随之更新。

这是其中一个combobox的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; }
    }
}

这个不起作用......我不知道为什么。


你是在什么时候更新 myObject.MyProperty,是在赋值 this.StackPanel_MyStackPanel.DataContext = myObject 之前还是之后? - Clemens
我想将comboBox的Text属性绑定到MyObject.MyProperty,ComboBox的ItemSource绑定到代码后台中的某个集合 - 我没有在这里提到是哪个集合。 - N.D
@Clemens 在我执行这个语句后,this.StackPanel_MyStackPanel.DataContext = myObject - N.D
1
然后类MyObject需要实现INotifyPropertyChanged并在MyProperty改变时触发PropertyChanged事件。 - Clemens
好的.....你是对的...我现在会做,然后告诉你是否解决了我的问题.... - N.D
2个回答

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"));
            }
        } 
    } 
} 

0

对我来说它是有效的...

顺便提一下,ItemsSource 是用于 ComboBox 中的项目,你不需要在这里设置它

我添加了一个按钮来测试它... 这是我的代码后台:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接