【问题标题】:WPF multiple bindings of one propertyWPF 一个属性的多个绑定
【发布时间】:2018-01-27 21:43:11
【问题描述】:

是否可以将一个属性绑定到多个控件?

例如,我想制作两个控件,它们可以在点击时增加一个值,并且都可以访问这个总和。

<Grid>
    <local:CustomControl Name="Control1" CommonValue="0"/>
    <local:CustomControl Name="Control2" CommonValue="0"/>
    <TextBlock Name="Counter" Text="{<binding to Control1.CommonValue and Control2.CommonValue>}"/>
</Grid>

public partial class CustomControl : UserControl, INotifyPropertyChanged
{
    ...

    private void UserControl_MouseDown(object sender, MouseButtonEventArgs e)
    {
        CommonValue = (int.Parse(CommonValue) + 1).ToString();
    }

    private string commonValue= "0";

    public event PropertyChangedEventHandler PropertyChanged;

    public string CommonValue
    {
        get { return commonValue; }
        set
        {
            commonValue = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("CommonValue"));
        }
    }

【问题讨论】:

  • 您想显示 control1.CommonValue 和 control2.CommonValue 的总和并在文本块中显示结果,对吗?如果是这样,您可以使用转换器进行多重绑定,将 2 个数字相加并返回结果
  • @Milan 不,我想从CustomControl s 获得总和

标签: c# wpf binding


【解决方案1】:

您需要在 CustomControl 上有一个依赖属性。您可以将其用于绑定。 (依赖属性用于绑定)

public static readonly DependencyProperty MyCustomProperty = 
DependencyProperty.Register("MyCustom", typeof(string), typeof(CustomControl));

public string MyCustom
{
    get
    {
        return this.GetValue(MyCustomProperty) as string;
    }
    set
    {
        this.SetValue(MyCustomProperty, value);
    }
}

之后:

<local:CustomControl Name="Control2" MyCustom="{Binding Path=CounterValue, Mode=TwoWay}"/>
<local:CustomControl Name="Control2" MyCustom="{Binding Path=CounterTwo, Mode=TwoWay}"/>

您可以使用运行文本:

<TextBlock>
<Run Text="{Binding CounterOne, Mode=OneWay}"/>
<Run Text="{Binding CounterTwo, Mode=OneWay}"/>
</TextBlock>

您还可以绑定到元素属性。

【讨论】:

  • 我怎样才能将绑定添加到Counter
  • 这很简单,更新了答案。您可以从 ViewModel 中为所有控件绑定属性。
猜你喜欢
  • 2010-12-05
  • 1970-01-01
  • 2012-02-08
  • 2014-06-07
  • 2018-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多