gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:03:41 24 4
gpt4 key购买 nike

我附上了一些 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com