代码之家  ›  专栏  ›  技术社区  ›  Jake Wharton

基于绑定对象和模型属性的可见绑定

  •  2
  • Jake Wharton  · 技术社区  · 15 年前

    我今天遇到了一个独特的情况,我需要把 Visible 中按钮的属性 DataGridRow 基于绑定对象的属性和支持它的模型。

    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 属性设置为转换器或其他对象上的静态方法。有什么想法吗?

    1 回复  |  直到 15 年前
        1
  •  1
  •   Heinzi    15 年前

    首先,不能直接使用布尔值作为可见性。你需要使用 BooleanToVisibilityConverter .

    第二,关于 ,您有不同的选项:

    1. 创建只读属性 IsEditableOrAdmin 在里面 Whatever 返回所需的值。缺点:您的 无论什么 需要对 TheModel .

    2. 使用多重绑定并写入 IMultiValueConverter . 然后,通过 二者都 多绑定中的值。自从 模型 此时不再在DataContext作用域中,可以使用 ElementName 用于引用UI元素的绑定的属性,其中 模型 仍然可以访问。

      示例(未测试):

      <SomeElementOutsideYourDataGrid Tag="{Binding TheModel}" />
      ...
          <Button>
              <Button.Visibility>
                  <MultiBinding Converter="{StaticResource yourMultiValueConverter}">
                      <Binding Path="IsEditable" />
                      <Binding ElementName="SomeElementOutsideYourDataGrid" Path="Tag.IsAdmin"/>
                  </MultiBinding>
              </Button.Visibility>
          </Button>
      
    3. 使用更强大的绑定框架,如 PyBinding .