c# - WPF C# 绑定(bind)代码 - 为什么这个简单的示例不起作用?

标签 c# .net wpf binding

我附上了一些 WPF C# 绑定(bind)代码 - 为什么这个简单的示例不起作用? (只是想了解绑定(bind)到自定义对象)。也就是说,当单击按钮以增加模型中的计数器时,标签不会更新。

<Window x:Class="testapp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button  Height="23" HorizontalAlignment="Left" Margin="20,12,0,0" 
                 Name="testButton" VerticalAlignment="Top" Width="126" 
                 Click="testButton_Click" Content="Increase Counter" />
        <Label Content="{Binding Path=TestCounter}" Height="37" 
               HorizontalAlignment="Right" Margin="0,12,122,0" 
               Name="testLabel2" VerticalAlignment="Top" 
               BorderThickness="3" MinWidth="200"  />
    </Grid>
</Window>


namespace testapp1
{
    public partial class MainWindow : Window
    {
        public TestModel _model;

        public MainWindow()
        {
            InitializeComponent();

            InitializeComponent();
            _model = new TestModel();
            _model.TestCounter = 0;
            this.DataContext = _model;
        }

        private void testButton_Click(object sender, RoutedEventArgs e)
        {
            _model.TestCounter = _model.TestCounter + 1;
            Debug.WriteLine("TestCounter = " + _model.TestCounter);
        }
    }

    public class TestModel : DependencyObject
    {
        public int TestCounter { get; set; }
    }

}

谢谢

最佳答案

对于这个简单的示例,请考虑使用 INotifyPropertyChanged 而不是 DependencyProperties!

更新 如果您确实想使用 DP,请使用 VS2010 中的 propdp 片段或 Dr WPF's snippets for VS2008

关于c# - WPF C# 绑定(bind)代码 - 为什么这个简单的示例不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3664968/

相关文章:

c# - 与 lambda 不同()?

c# - 将两个图像合并为一个新图像

c# - WCF 服务在处理特殊字符时失败

.net - 揭开依赖属性的神秘面纱

c# - 当方向改变时,如何防止 Xamarin Forms ScrollView 中的内容卡住?

c# - 在 ListView 控件中访问 TextBox 控件

c# - 类似实体的类

c# - 将样式应用于所有 TreeViewItem

c# - WPF 是否可以在 Windows 锁定屏幕顶部显示dialog()?

C# 和 USB HID 设备