【问题标题】:How do I bind to a property?如何绑定到属性?
【发布时间】:2011-03-24 11:15:32
【问题描述】:

这是我的简化方案。我可以使用鼠标调整我的内部矩形宽度。一个文本块显示宽度,当我调整它时会发生变化。我想要第二个文本块来显示一个属性的值,该值也随宽度而变化,但我不知道如何绑定它。

<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;
    }          
}

【问题讨论】:

    标签: c# silverlight binding


    【解决方案1】:

    您的 MainPage 必须实现 INotifyPropertyChanged 接口(@98​​7654322@ 的示例)并且您的属性必须在设置时触发事件,或者您必须将 Dependency property 用于 Value .
    同样在 myRec_MouseMove 处理程序上,将宽度分配给 Value 属性,而不是 _value 成员。

    【讨论】:

      【解决方案2】:

      您必须将属性“Value”声明为依赖属性。

      【讨论】:

        【解决方案3】:

        在您的代码隐藏中:

        myText2.DataContext = Value;
        

        在您的 xaml 中:

        <TextBlock x:Name="myText2" Width="40" Height="20" Foreground="White" Text="{Binding Path=.}" />
        

        “路径=。”将指向您的数据上下文。

        【讨论】:

          猜你喜欢
          • 2017-05-26
          • 2018-08-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-11-26
          相关资源
          最近更新 更多