AndrewR
AndrewR

Reputation: 624

WPF multiple bindings of one property

Is it possible to bind one property to multiple controls?

For example, I'd like to make two controls that can increment one value on click and both have access to this sum.

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

Upvotes: 2

Views: 2185

Answers (1)

J&#225;nos Tigyi
J&#225;nos Tigyi

Reputation: 397

You need to have a dependency property on CustomControl. You can use it for Binding. (Dependency property is for binding)

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

After this:

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

You can use Run Text:

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

You can also bind to an element property.

Upvotes: 3

Related Questions