【问题标题】:Visible Binding Based On Bound Object and Model Properties基于绑定对象和模型属性的可见绑定
【发布时间】:2025-12-28 06:00:11
【问题描述】:

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

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 属性传递给转换器或其他东西上的静态方法。有什么想法吗?

【问题讨论】:

    标签: c# .net wpf xaml binding


    【解决方案1】:

    首先,您不能直接使用布尔值来表示可见性。您需要使用BooleanToVisibilityConverter

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

    1. Whatever 中创建一个只读属性IsEditableOrAdmin,它返回您想要的值。缺点:您的Whatever 需要反向引用TheModel

    2. 使用 MultiBinding 并编写 IMultiValueConverter。然后,在 MultiBinding 中传递 both 值。由于此时 TheModel 不再位于 DataContext 范围内,因此您可以使用 Binding 的 ElementName 属性来引用仍可访问 TheModel 的 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

    【讨论】:

    • 该示例是已经使用自定义转换器的实际实现的高度简化版本。更改为IMultiValueConverter 并通过两者就可以了。谢谢!