PropertyChanged不适用于绑定

时间:2016-04-04 08:37:50

标签: c# wpf xaml textbox propertychanged

我有一个由财产填充的文本框。当我单击按钮时,属性值会更改,文本框内容也应该更改。但是我的财产改变了事件并没有奏效。我已经在这里和其他来源搜索了解决方案。我找不到任何有用的东西。有人能帮助我吗?

代码:

using System.ComponentModel;

namespace TestWPF {
    public class Class1 : INotifyPropertyChanged {

        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string name) {
            if (PropertyChanged != null) {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }

        private string test = "test";
        public string TestProperty {
            get { return test; }
            set {
                if (value != test)
                    test = value;
                OnPropertyChanged("TestProperty");
            }
        }
    }
}

<Window.DataContext>
<local:Class1/>
</Window.DataContext>
<Grid>
    <TextBox Text="{Binding Path=TestProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" x:Name="textBox" HorizontalAlignment="Center" Margin="0,-100,0,0" Height="69" TextWrapping="Wrap"  VerticalAlignment="Center" Width="255"/>
    <Button x:Name="button" Content="Button" HorizontalAlignment="Center" Margin="0,0,0,0" VerticalAlignment="Center" Width="75" Click="button_Click"/>
</Grid>

编辑:

        private void button_Click(object sender, RoutedEventArgs e) {
        cs1.TestProperty = "Test button";
    }

1 个答案:

答案 0 :(得分:0)

private void button_Click(object sender, RoutedEventArgs e) 
{
        var dc = (sender as System.Windows.Controls.Button).DataContext;
        var cs1 = dc as Class1;
        cs1.TestProperty = "Test button";
}

public partial class MainWindow : Window
{

    Class1 cs1;

    public MainWindow()
    {
        InitializeComponent();
        DataContext = cs1 = new Class1();
    }

    private void button_Click(object sender, RoutedEventArgs e) 
    {
       cs1.TestProperty = "Test button";
    }
}

没有:

<Window.DataContext>
   <local:Class1/>
</Window.DataContext>