C# 如何绑定到属性?
这是我的简化方案。我可以用鼠标调整内部矩形的宽度。一个文本块显示我调整它时改变的宽度。我需要第二个textblock来显示属性的值,该属性的值也会随着宽度的变化而变化,但我不知道如何绑定它C# 如何绑定到属性?,c#,silverlight,binding,C#,Silverlight,Binding,这是我的简化方案。我可以用鼠标调整内部矩形的宽度。一个文本块显示我调整它时改变的宽度。我需要第二个textblock来显示属性的值,该属性的值也会随着宽度的变化而变化,但我不知道如何绑定它 <Grid x:Name="LayoutRoot" Background="White" VerticalAlignment="Center"> <Rectangle x:Name="aRec" Height="100" Width="100" MinWidth="10" Fill
<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="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;
}
}
公共部分类主页面:UserControl
{
布尔活动=假;
私人双重价值;
公共双重价值
{
获取{返回_值;}
设置{u value=value;}
}
公共主页()
{
初始化组件();
}
私有void myRec_MouseLeftButtonDown(对象发送器,MouseButtonEventArgs e)
{
主动=真;
}
私有void myRec_MouseMove(对象发送方,MouseEventArgs e)
{
如果(活动==真)
{
aRec.Width=e.GetPosition(myRec).X;
_值=平均宽度*10;
}
}
私有void myRec_MouseLeftButtonUp(对象发送器,MouseButtonEventArgs e)
{
主动=假;
}
}
必须将属性“Value”声明为依赖属性。在代码隐藏中:
myText2.DataContext = Value;
在您的xaml中:
<TextBlock x:Name="myText2" Width="40" Height="20" Foreground="White" Text="{Binding Path=.}" />
“Path=”将指向您的datacontext。您的主页面必须实现接口(例如),并且您的属性必须在设置时触发事件,或者您必须使用for Value。另外,在myRec_MouseMove hanlder上,将宽度指定给Value属性,而不是_Value成员