代码之家  ›  专栏  ›  技术社区  ›  AndrewR

WPF一个属性的多个绑定

  •  1
  • AndrewR  · 技术社区  · 7 年前

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

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

    <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"));
            }
        }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   János Tigyi    7 年前

    您需要在CustomControl上具有dependency属性。您可以使用它进行绑定。(Dependency属性用于绑定)

    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>
    

    还可以绑定到元素属性。