首先,让我说一下我完全是C#的新手。目前,我正在开发一个程序,并且一直在尝试获得一些我认为很简单的东西。显然不是这样。我将在这里展示我一直在尝试做的一个非常小的例子。这在功能上是相同的,但是没有我在实际项目中拥有的所有其他东西。这里有3个文件。
MainWindow.xaml
<Window.Resources>
<CollectionViewSource x:Key="data1ViewSource" d:DesignSource="{d:DesignInstance {x:Type local:Data1}, CreateList=True}"/>
</Window.Resources>
<Grid>
<Button x:Name="TestButton" Content="Button" HorizontalAlignment="Left" Margin="78,25,0,0" VerticalAlignment="Top" Width="75" Click="TestButton_Click"/>
<TextBox x:Name="testStringTextBox" HorizontalAlignment="Left" Height="24" Margin="78,86,0,309" Grid.Row="0" Text="{Binding TestString}" VerticalAlignment="Center" Width="120"/>
<TextBlock x:Name="testStringTextBlock" HorizontalAlignment="Left" Margin="78,143,0,0" TextWrapping="Wrap" Text="{Binding TestString}" VerticalAlignment="Top" Height="181" Width="245"/>
</Grid>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void TestButton_Click(object sender, RoutedEventArgs e)
{
Class1.TheButton();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
System.Windows.Data.CollectionViewSource data1ViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("data1ViewSource")));
// Load data by setting the CollectionViewSource.Source property:
// data1ViewSource.Source = [generic data source]
}
}
Class1.cs
public static class Class1
{
private static int Inc = 1;
public static Data1 testData = new Data1("Starting test\n");
public static void TheButton()
{
testData.TestString += "Test number " + Inc.ToString() + ".\n";
Inc++;
}
}
public class Data1 : INotifyPropertyChanged
{
public Data1(string input)
{
TestString = input;
}
private string _testString;
public event PropertyChangedEventHandler PropertyChanged;
public string TestString
{
get { return _testString; }
set { _testString = value; OnPropertyChanged("TestString"); }
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
程序按原样编译,没有错误,当我设置断点时,我可以查看对象Class1.testData,并且可以在Class1.testData.TestString和_testString中看到正确的值。
我已经花了几天的时间来寻找某种简单我在这里尝试做的事的例子,但是我还没有找到任何使它真正起作用的解决方案。我得出的结论是,我必须做错了什么,或者只是遗漏了一些东西,但是我也找不到任何东西可以让我了解到那是什么。
答案 0 :(得分:2)
将xaml更改为使用x:Static
并提供Path
:
<Canvas>
<Button x:Name="TestButton" Content="Button" HorizontalAlignment="Left" Margin="78,25,0,0" VerticalAlignment="Top" Width="75" Click="TestButton_Click"/>
<TextBox x:Name="testStringTextBox"
HorizontalAlignment="Left"
Height="24"
Margin="78,86,0,309"
Text="{Binding Source={x:Static local:Class1.testData}, Path=TestString}"
VerticalAlignment="Center"
Width="120"/>
<TextBlock x:Name="testStringTextBlock"
HorizontalAlignment="Left"
Margin="78,143,0,0"
TextWrapping="Wrap"
Text="{Binding Source={x:Static local:Class1.testData}, Path=TestString}"
VerticalAlignment="Top"
Height="181"
Width="245"/>
</Canvas>
还请注意,如果您在文本框中输入值,则只有当文本框失去焦点时,该值才会在变量中更新。