[英]Visible Binding Based On Bound Object and Model Properties
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. 今天,我遇到了一种独特的情况,我需要在DataGridRow
绑定按钮的Visible
属性,使其同时基于绑定对象的属性和支持该对象的模型。
XAML: 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>
Model: 模型:
class TheModel
{
public ObservableCollection<Whatever> Items { get; set; }
public bool IsAdmin { get; set; }
}
Class: 类:
class Whatever
{
public bool IsEditable { get; set; }
}
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. 我认为可能可行的唯一概念是以某种方式将绑定的对象以及整个模型或仅将IsAdmin
属性传递给转换器上的静态方法或其他方法。 Any ideas? 有任何想法吗?
Firstly, you cannot directly use a Boolean for Visibility. 首先,您不能直接将布尔值用于可见性。 You need to use the BooleanToVisibilityConverter . 您需要使用BooleanToVisibilityConverter 。
Secondly, about the OR , you have different options: 其次,关于OR ,您有不同的选择:
Create a readonly property IsEditableOrAdmin
in Whatever
which returns the value you want. 在Whatever
创建一个只读属性IsEditableOrAdmin
,该属性将返回所需的值。 Drawback: Your Whatever
will need a back-reference to TheModel
. 缺点: Whatever
您需要Whatever
都需要对TheModel
的反向引用。
Use a MultiBinding and write an IMultiValueConverter . 使用MultiBinding并编写一个IMultiValueConverter 。 Then, pass both values in the MultiBinding. 然后,在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. 由于TheModel
不再位于DataContext范围内,因此您可以使用Binding的ElementName
属性来引用仍可访问TheModel
的UI元素。
Example (untested): 示例(未试用):
<SomeElementOutsideYourDataGrid Tag="{Binding TheModel}" /> ... <Button> <Button.Visibility> <MultiBinding Converter="{StaticResource yourMultiValueConverter}"> <Binding Path="IsEditable" /> <Binding ElementName="SomeElementOutsideYourDataGrid" Path="Tag.IsAdmin"/> </MultiBinding> </Button.Visibility> </Button>
Use a more powerful binding framework such as PyBinding . 使用更强大的绑定框架,例如PyBinding 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.