WPF - 在转换器中检测设计模式 [英] WPF - Detect design mode in a Converter

查看:35
本文介绍了WPF - 在转换器中检测设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个转换器,我希望能够在 DesignMode 中将值更改为 Visibility.Collapsed.没错,它忽略了 GetIsInDesignMode.

I have a converter in which I want to be able to change the value to Visibility.Collapsed when in DesignMode. Right it is ignoring the GetIsInDesignMode.

另外,我通过依赖注入(prism)绑定虚拟机

Also, I am binding the VM via dependency injectio (prism)

转化者:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {

        if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            return Visibility.Collapsed;

        if (value != null && value is AllowedSourceCode)
        {
            var allowedSourceCode = (AllowedSourceCode)value;

            if (value == null)
                return Visibility.Visible;
            else if (allowedSourceCode.SupportedSourceCodes.Contains(allowedSourceCode.SelectedSourceCode))
            {
                return Visibility.Collapsed;
            }
            else
            return Visibility.Visible;

        }
        return Visibility.Collapsed;
    }

查看:

        <Canvas Visibility="{Binding SupportedSourceCodes,Converter={StaticResource AllowedSourcesConverter}}" Background="Gray" Opacity="0.9"
            Grid.Row="0" Grid.Column="0" Grid.RowSpan="3" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Panel.ZIndex="5"  >

xaml.cs:

        public ACARSubLedgerUC(ACARSubLedgerVM vm)
    {
        InitializeComponent();
        DataContext = vm;
    }

推荐答案

你所做的应该有效.

我猜你的窗口后面有一个视图模型,并在绑定到该视图模型上使用转换器.请确保您在 XAML 中而不是在代码中设置您的数据上下文,因为如果您在代码中设置它,您的转换器将永远不会在设计模式下运行.

I'm guessing you have a viewmodel behind your window and using the converter on a binding to that viewmodel. Please make sure you are setting your data context in XAML and not in code, because if you are setting it in code your converter will never hit in design mode.

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:local="clr-namespace:WpfApp1"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        Title="MainWindow"
        Width="525"
        Height="350"
        mc:Ignorable="d">

    <Window.DataContext>
        <local:ViewModel />
    </Window.DataContext>

    ...

</Window>

这可确保在设计时更新绑定,因此将调用您的转换器.

This ensures bindings are updated at design time and hence your converter will be called.

这篇关于WPF - 在转换器中检测设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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