【问题标题】:View property - bind twice查看属性 - 绑定两次
【发布时间】:2016-03-17 13:18:02
【问题描述】:

是否可以多次绑定控件的同一个属性?

举例:

<Popup IsOpen="{Binding Path=(local:ListViewBehavior.IsColumnHeaderClicked),
    RelativeSource={RelativeSource FindAncestor,  AncestorType=GridViewColumnHeader}}" ...

如您所见,Popup.IsOpen 绑定到附加属性。我想将它绑定到 ViewModel IsPopupOpened,但不知道如何。


尝试@Arhiman 的答案但没有成功:

<Popup.IsOpen>
    <MultiBinding Converter="{local:MultiBindingConverter}">
        <Binding Path="(local:ListViewBehavior.IsColumnHeaderClicked)"
                 RelativeSource="{RelativeSource FindAncestor, AncestorType=GridViewColumnHeader}" />
        <Binding Path="DataContext.IsPopupId"
                 RelativeSource="{RelativeSource FindAncestor, AncestorType=UserControl}" />
    </MultiBinding>
</Popup.IsOpen>

朴素转换器逻辑:

public class MultiBindingConverter : MarkupExtension, IMultiValueConverter
{
    public MultiBindingConverter() { }

    public override object ProvideValue(IServiceProvider serviceProvider) => this;

    object[] _old;

    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (_old == null)
            _old = values.ToArray();
        // check if one of values is changed - that change is a new value
        for (int i = 0; i < values.Length; i++)
            if (values[i] != _old[i])
            {
                _old = values.ToArray();
                return values[i];
            }
        return values[0];
    }

    // replicate current value
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) =>
        Enumerable.Repeat(value, targetTypes.Length).ToArray();
}

【问题讨论】:

    标签: c# wpf mvvm binding


    【解决方案1】:

    您可以简单地使用带有转换器的 MultiBinding 来实现您想要的逻辑。

    <Popup.IsOpen>
        <MultiBinding Converter="{StaticResource openLogicConverter}">
            <Binding Path="MyAttachedProperty" ... />
            <Binding Path="IsPopupOpened" />
        </MultiBinding>
    </Popup.IsOpen>
    

    我通常会将这个逻辑放在 ViewModel 中,但由于它是一个 AttachedProperty,直接在 View 中的东西对我来说似乎更合适。

    【讨论】:

    • 我还不能让它工作。想法很清楚,但问题是转换器逻辑。通常,您在 ViewModel 中有属性,然后绑定了多个控件。当任何一个控件或 ViewModel 本身更改属性时 - 所有控件都会更新。我想要一些镜像:单个控件绑定到多个属性。当任一属性发生更改时 - 应更新所有其他属性和控件。你能展示openLogicConverter 在绑定之间传递 值的样子吗?见编辑。
    • 我宁愿尝试为我描述的场景创建 mcve 并提出另一个问题。
    • 我好像没听懂你的问题。实际上我可能需要一些澄清,比如场景中的不同参与者是什么,属性是什么,影响什么等等。此外,是否可以将所有这些属性集中到 ViewModel 中,而不是使用行为?然后这个 ViewModel 属性适合主人的角色,在一个类似主从的范式中。取决于此 ListView 是否可以绑定到 ViewModel。
    • Here。我将问题简化为简单的重现。
    • 我不确定我是否完全明白,所以我将添加此评论,如果仍然不是正确答案,请见谅。我有一个 ColumnHeaderViewModel 或其他东西的实例,它被传递给 PopUp 中使用的 ViewModel 和 ListView 中使用的 ViewModel。这个 ColumnHeaderVM 将拥有您需要的属性(之前在 AttachedProperty 和 Popup 的 ViewModel 中)。 CHVM 中的这个属性也将替换您的 AttachedProperty,并将用于 IsOpen 绑定。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    相关资源
    最近更新 更多