I play with WPF binding and variables. Apparently, you can only bind DependencyProperties. I came up with the following that works great: File with code:
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } public string Test { get { return (string)this.GetValue(TestProperty); } set { this.SetValue(TestProperty, value); }
XAML:
<Window x:Class="WpfApplication3.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase" Title="MainWindow" Height="350" Width="525" DataContext="{Binding RelativeSource={RelativeSource Self}}"> <Grid> <TextBox Height="31" HorizontalAlignment="Left" Margin="84,86,0,0" Name="textBox1" VerticalAlignment="Top" Width="152" Text="{Binding Test, Mode=TwoWay, diag:PresentationTraceSources.TraceLevel=High}"/> <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="320,85,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" /> <TextBox Height="31" HorizontalAlignment="Left" Margin="84,138,0,0" Name="textBox2" Text="{Binding Test, Mode=TwoWay}" VerticalAlignment="Top" Width="152" /> </Grid>
Two text blocks update one another. And the button sets them to "AAA".
But now I have replaced the Setter function with what is commented out (simulating some manipulations with this value). I would expect that whenever the property value is changed, it will be reset to "BBB". It does this when you click the button, that is, when you set the property in code. But for some reason, this does not affect WPF bindings, that is, you can change the contents of the TextBox and, therefore, the property, but, apparently, Setter is never called. I wonder why this is so, and how the expected behavior could be achieved.
c # wpf binding xaml dependency-properties
PeterE
source share