【发布时间】:2014-02-14 06:30:33
【问题描述】:
我正在制作一个基本程序,当用户在文本框中键入时,标签会更新。我正在尝试使用数据绑定和 INotifyPropertyChanged 来解决这个问题,所以我不想要任何解决方法。我使用了 2 个按钮,所以我实际上可以查看它们是否更新。这是我的主要课程
namespace TestStringChangeFromAnotherClass
public partial class MainWindow : Window
{
textClass someTextClass = new textClass();
public MainWindow()
{
InitializeComponent();
}
public string someString1;
public string someString2;
private void btn1_Click(object sender, RoutedEventArgs e)
{
someTextClass.Text1 = tbx1.Text;
}
private void btn2_Click(object sender, RoutedEventArgs e)
{
someTextClass.Text2 = tbx1.Text;
}
}
这是它的 wpf
<Window x:Class="TestStringChangeFromAnotherClass.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button x:Name="btn1" Content="Button" HorizontalAlignment="Left" Height="36" Margin="29,246,0,0" VerticalAlignment="Top" Width="108" Click="btn1_Click"/>
<Button x:Name="btn2" Content="Button" HorizontalAlignment="Left" Height="36" Margin="227,246,0,0" VerticalAlignment="Top" Width="124" Click="btn2_Click"/>
<Label x:Name="lbl1" Content="{Binding textClass.Text1}" HorizontalAlignment="Left" Height="37" Margin="74,32,0,0" VerticalAlignment="Top" Width="153"/>
<Label x:Name="lbl2" Content="{Binding textClass.Text2, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Height="38" Margin="74,90,0,0" VerticalAlignment="Top" Width="153"/>
<TextBox x:Name="tbx1" HorizontalAlignment="Left" Height="37" Margin="290,32,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="190"/>
</Grid>
如您所见,我已尝试使用 UpdateSourceTrigger。我还尝试使用“someTestClass.Text1”而不是 textClass.Test1,因为这就是我在 MainWindow 中定义它的方式。这是我的文本类
namespace TestStringChangeFromAnotherClass
public class textClass:INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string text1;
public string Text1
{
get { return text1; }
set
{
text1 = value;
NotifyPropertyChanged("Text1");
}
}
private string text2;
public string Text2
{
get { return text2; }
set
{
text2 = value;
NotifyPropertyChanged("Text2");
}
}
protected void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
我不知道如何让 wpf 在单独的类中查找 Test1 或 Test2 字符串并在字符串更改时更新它们。我感觉问题出在 DataContext 中,但我想不通。我也宁愿不在 c# 中使用 DataContext,只在 WPF 中使用
更新: 当我调试它时,当它到达 NotifyPropertyChanged 时,PropertyChanged 被评估为空。会不会是这个问题?
【问题讨论】:
-
您是否也尝试过在 Mainwindow 中实现 INotifyPropertyChanged?因为这是您的数据上下文。
-
如果我在 MainWindow 中添加 INotifyPropertyChanged,我会收到此错误 -'TestStringChangeFromAnotherClass.MainWindow' 没有实现接口成员 'System.ComponentModel.INotifyPropertyChanged.PropertyChanged'
-
也许,我需要做的是尝试让 UpdateSourceTrigger 查看 textClass 类中的 PropertyChanged 项?
标签: c# wpf properties inotifypropertychanged