我正在製作一個基本程序,當用戶在文本框中輸入內容時,標籤會更新。我試圖使用數據綁定和INotifyPropertyChanged解決這個問題,所以我不想要任何解決方法。我使用了2個按鈕,所以我實際上可以看到他們是否更新。這裏是我的主類無法從另一個類中的wpf獲取標籤
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中定義它的方式。這裏是我的textClass
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被評估爲null。這可能是問題嗎?
你有沒有嘗試在Mainwindow中實現INotifyPropertyChanged呢?因爲這是你的數據上下文。 – TylerD87
如果我在MainWindow中添加INotifyPropertyChanged,我得到這個錯誤-'TestStringChangeFromAnotherClass。MainWindow'沒有實現接口成員'System.ComponentModel.INotifyPropertyChanged.PropertyChanged' – darthwillard
也許,我需要做的是嘗試讓UpdateSourceTrigger查看TextClass類中的PropertyChanged項目? – darthwillard