是否可以将一个属性绑定到多个控件?
例如,我想制作两个控件,可以在点击时增加一个值,并且都可以访问此总和。
<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"));
}
}
答案 0 :(得分:2)
您需要在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>
您还可以绑定到元素属性。