c# - WPF 一个属性的多个绑定(bind)

标签 c# wpf binding

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

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

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

最佳答案

您需要具有 CustomControl 的依赖属性。您可以将其用于绑定(bind)。 (依赖属性用于绑定(bind))

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>

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

关于c# - WPF 一个属性的多个绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48480866/

相关文章:

node.js - 在 Node.js 应用程序中启动时无法找到绑定(bind)文件

c# - 我如何将 "Thread.Join"设置为 BackgroundWorker?

c# - 如何创建一个行为类似于 Session[] 集合的集合? C#

c# - 具有两个 ScrollViewer 的 WPF Split View

c# - 如何设置<Linebreak/>的高度

.NET WPF XAML "BindingExpression path error: ... property not found"

c# - 使用通配符或 "tags"进行用户输入

c# - 有没有办法实现 ZeroMQ 全双工 channel ?

c# - Microsoft.Windows.Controls 是否缺少程序集引用?

c# - WPF:当某个值更改时重新应用 DataTemplateSelector