wpf - 根据对象类型取消绑定(bind)

标签 wpf data-binding

在我的 WPF 应用程序中,我有一个与文本属性的长度绑定(bind)的标签:

<Label Content="{Binding Editor.Text.Length}"/>

编辑器对象可以是文本框或复选框。文本框确实有 Text-property,而复选框则没有。
当标签绑定(bind)到“复选框编辑器”时,它会在 Visual Studio 中生成警告:

BindingExpression path error: 'Text' property not found on 'object'...

这是预期的,我想知道是否有任何方法可以告诉绑定(bind)引擎不要尝试绑定(bind)此值,除非编辑器对象是文本框?

最佳答案

View 模型的 Editor 属性是控件吗?我希望不会,但无论如何。

您可以编写一个返回值类型的值转换器,然后通过样式中的一系列触发器设置标签的内容。如果编辑器的类型是 {x:Type TextBox},请将其设置为上面的绑定(bind)。如果是 {x:Type CheckBox},请将其设为“{Binding Editor.IsChecked}”。

XAML

<Label>
    <Label.Style>
        <Style TargetType="Label" BasedOn="{StaticResource {x:Type Label}}">
            <Style.Triggers>
                <DataTrigger 
                    Binding="{Binding ElementName=Editor, Converter={local:GetTypeConverter}}"
                    Value="{x:Type TextBox}"
                    >
                    <Setter 
                        Property="Content" 
                        Value="{Binding Text.Length, ElementName=Editor}" 
                        />
                </DataTrigger>
                <DataTrigger 
                    Binding="{Binding ElementName=Editor, Converter={local:GetTypeConverter}}"
                    Value="{x:Type CheckBox}"
                    >
                    <Setter 
                        Property="Content" 
                        Value="{Binding IsChecked, ElementName=Editor}" 
                        />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Label.Style>
</Label>

C#

public class GetTypeConverter : MarkupExtension, IValueConverter
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value?.GetType();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

或者,您的 View 模型可以有一个只读属性,该属性返回该标签中应包含的任何内容,因为 View 模型具有 Editor 并且知道它是什么。暂时将其称为 EditorLabelValue。据推测,Editor 绑定(bind)到 string 属性或 bool 属性,具体取决于它是哪个编辑器。因此,这两个 setter 都会为 "EditorLabelValue" 引发 PropertyChanged,这将返回适当的值。

我尝试在纯 XAML 中通过将 Editor 设为 ContentControlContent 然后使用 DataTemplates 来实现此目的,但我做不到。没有找到一种方法来实现这一点,而不会出现重新设置Editor的异常。

关于wpf - 根据对象类型取消绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39167238/

相关文章:

c# - 检测悬停在 ViewModel 中的 ListBoxItem 上

.net - 绑定(bind)自动分离的情况

c# - 如何将分层数据数据绑定(bind)到 WPF TreeView?

c# - 我的 MEF 导出有问题吗?

c# - 具有多个源数据和分组列的 WPF DataGrid

c# - WPF ListView ItemTemplate问题

c# - 列标题中带有点的 WPF Datagrid 绑定(bind)错误

Wpf 组合框与父/子表的数据绑定(bind)

c# mvvm IEqualityComparer with IChangeTracking

c# - 从 WPF 客户端访问安全的 Web API