How do I bind to a property?
Here's my simplified scenario. I can adjust my inner rectangle width using the mouse. A textblock displays the width which changes as I adjust it. I want a second textblock to display the value of a property which also changes with the width but I cannot figure out how to bind it.
<Grid x:Name="LayoutRoot" Background="White" VerticalAlignment="Center">
<Rectangle x:Name="aRec" Height="100" Width="100" MinWidth="10" Fill="Blue" />
<Rectangle x:Name="myRec" Height="100" Width="300" MinWidth="10" Fill="Red" Opacity="0.5"
MouseLeftButtonDown="myRec_MouseLeftButtonDown"
MouseLeftButtonUp="myRec_MouseLeftButtonUp"
MouseMove=开发者_JS百科"myRec_MouseMove"></Rectangle>
<StackPanel>
<TextBlock x:Name="myText1" Width="40" Height="20" Foreground="White" Text="{Binding ElementName=aRec, Path=Width}" />
<TextBlock x:Name="myText2" Width="40" Height="20" Foreground="White" Text="{Binding Value}" />
</StackPanel>
</Grid>
public partial class MainPage : UserControl
{
Boolean active = false;
private Double _value;
public Double Value
{
get { return _value; }
set { _value = value; }
}
public MainPage()
{
InitializeComponent();
}
private void myRec_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
active = true;
}
private void myRec_MouseMove(object sender, MouseEventArgs e)
{
if (active == true)
{
aRec.Width = e.GetPosition(myRec).X;
_value = aRec.Width * 10;
}
}
private void myRec_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
active = false;
}
}
You MainPage must implement INotifyPropertyChanged interface (example for How to: Implement the INotifyPropertyChanged Interface) and your properties must fire event on set, or you must use Dependency property for Value.
Also on myRec_MouseMove hanlder assign width to Value property, not _value member.
You have to declare the property "Value" as a dependency property.
In your code-behind:
myText2.DataContext = Value;
In your xaml:
<TextBlock x:Name="myText2" Width="40" Height="20" Foreground="White" Text="{Binding Path=.}" />
"Path=." will point to your datacontext.
精彩评论