I'm new to Windows 8.1 development, as well as C# and XAML, so forgive me if this is a terribly rudimentary question. First, I used the following page as the inspiration for much of what I've done here:
https://msdn.microsoft.com/en-us/library/ms742863(v=vs.110).aspx
Here's the XAML of my page:
<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>
And here's my code-behind:
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";
}
}
}
What's happening is that the TextBox and TextBlock both get their Text property set to Initial Value of the 'str' variable
, but when I click the button and the underlying value of str
changes (which I verified is actually happening with breakpoints and step-through), the Text values of the TextBlock and TextBox do not change.
When I do the binding another way (i.e. in the XAML rather than in the code-behind), it does work. Here's all I did to make that happen:
<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>
So my main question is "How can I get the code-behind data binding to work, like the XAML-based binding works?".
Thanks in advance for any help, advice, or tips you can offer!