【发布时间】:2015-06-19 05:42:49
【问题描述】:
我是 Windows 8.1 开发以及 C# 和 XAML 的新手,如果这是一个非常初级的问题,请原谅我。首先,我使用以下页面作为我在这里所做的大部分工作的灵感:
https://msdn.microsoft.com/en-us/library/ms742863(v=vs.110).aspx
这是我页面的 XAML:
<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Button HorizontalAlignment="Left" Content="this is my button" Click="Button_Click" />
<TextBox Text="This is a bound text box" x:Name="BoundTextBox" />
<TextBlock Text="This is a bound text block" x:Name="BoundTextBlock" />
</StackPanel>
这是我的代码隐藏:
public sealed partial class MyPage : Page, INotifyPropertyChanged
{
#region Str variable
// Create the source string.
private string str = "Initial Value of the 'str' variable";
public string Str
{
get { return str; }
set {
str = value;
NotifyPropertyChanged("Str");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
...
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// Create the binding description.
Binding binding = new Binding(); // 'Binding' has no one-parameter constructors, so changed from MS's documentation
binding.Mode = BindingMode.OneWay; // I tried TwoWay, as well, but that also did not work
binding.Source = Str;
// Attach the binding to the target.
BoundTextBox.SetBinding(TextBox.TextProperty, binding);
BoundTextBlock.SetBinding(TextBlock.TextProperty, binding);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.TextColorBrush = new SolidColorBrush(Colors.Red);
if (Str == "Changed Value ONE")
{
Str = "SECOND Changed Value";
}
else
{
Str = "Changed Value ONE";
}
}
}
发生的情况是 TextBox 和 TextBlock 都将它们的 Text 属性设置为 Initial Value of the 'str' variable,但是当我单击按钮时,str 的基础值发生了变化(我验证这实际上是通过断点和单步执行发生的),TextBlock 和 TextBox 的 Text 值不会改变。
当我以另一种方式(即在 XAML 中而不是在代码隐藏中)进行绑定时,它确实起作用。以下是我为实现这一目标所做的一切:
<Page
x:Name="This"
...
>
<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Button HorizontalAlignment="Left" Content="this is my button" Click="Button_Click" />
<TextBox Text="{Binding ElementName=This, Path=Str, Mode=OneWay}" x:Name="BoundTextBox" />
<TextBlock Text="{Binding ElementName=This, Path=Str, Mode=OneWay}" x:Name="BoundTextBlock" />
</StackPanel>
</Page>
所以我的主要问题是“我怎样才能让代码隐藏数据绑定工作,就像基于 XAML 的绑定一样工作?”。
提前感谢您提供的任何帮助、建议或提示!
【问题讨论】:
标签: c# xaml windows-phone-8 data-binding code-behind