可见绑定基于绑定对象和模型属性 [英] Visible Binding Based On Bound Object and Model Properties

查看:149
本文介绍了可见绑定基于绑定对象和模型属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我跑的独特情况今天在这里,我需要绑定可见在按钮的财产 DataGridRow 要基于模型的被装订物的两个属性和支持它。

I ran in to the unique situation today where I needed to bind the Visible property of a button in a DataGridRow to be based on both a property of the bound object and of the model backing it.

XAML:

<t:DataGrid ItemsSource="{Binding Items}">
    <t:DataGrid.Columns>
        <t:DataGridTemplateColumn>
            <t:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Visibility="IsEditable OR IsAdmin"/>
                </DataTemplate>
            </t:DataGridTemplateColumn.CellTemplate>
        </t:DataGridTemplateColumn>
    </t:DataGrid.Columns>
</t:DataGrid>

型号:

class TheModel
{
    public ObservableCollection<Whatever> Items { get; set; }
    public bool IsAdmin { get; set; }
}

类:

class Whatever
{
    public bool IsEditable { get; set; }
}

这难倒我。我能想到的可能工作唯一的概念会以某种方式传递绑定的对象,要么整个模型或仅 IsAdmin 属性设置为一个静态方法上的转换器或什么的。任何想法?

This stumped me. The only concept that I could think might work would be somehow passing the bound object and either the entire model or just the IsAdmin property to a static method on a converter or something. Any ideas?

推荐答案

首先,你不能直接使用布尔的能见度。你需要使用<一个href="http://msdn.microsoft.com/en-us/library/system.windows.controls.booleantovisibilityconverter.aspx"相对=nofollow> BooleanToVisibilityConverter 。

Firstly, you cannot directly use a Boolean for Visibility. You need to use the BooleanToVisibilityConverter.

其次,有关的的,你有不同的选择:

Secondly, about the OR, you have different options:

  1. 在创建返回所需的值只读属性 IsEditableOrAdmin 。缺点:你的将需要一个反向引用到 TheModel

  1. Create a readonly property IsEditableOrAdmin in Whatever which returns the value you want. Drawback: Your Whatever will need a back-reference to TheModel.

使用一个MultiBinding,写一个 IMultiValueConverter 。然后,通过的在MultiBinding两个的值。由于 TheModel 不再在这一点上的DataContext范围内,您可以使用绑定的的ElementName 属性引用到UI元素,其中 TheModel 是仍然可以访问。

Use a MultiBinding and write an IMultiValueConverter. Then, pass both values in the MultiBinding. Since TheModel is no longer in the DataContext scope at that point, you could use the ElementName property of the Binding to refer to a UI element where TheModel is still accessible.

例(未经测试):

<SomeElementOutsideYourDataGrid Tag="{Binding TheModel}" />
...
    <Button>
        <Button.Visibility>
            <MultiBinding Converter="{StaticResource yourMultiValueConverter}">
                <Binding Path="IsEditable" />
                <Binding ElementName="SomeElementOutsideYourDataGrid" Path="Tag.IsAdmin"/>
            </MultiBinding>
        </Button.Visibility>
    </Button>

  • 使用更强大的具有约束力的框架,如 PyBinding

    这篇关于可见绑定基于绑定对象和模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆