WPF - 检测转换器中的设计模式

H20*_*der 6 c# wpf visual-studio-2015

我有一个转换器,我希望能够在设计模式下将值更改为 Visibility.Collapsed。没错,它忽略了 GetIsInDesignMode。

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

转换器:

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;
    }
Run Code Online (Sandbox Code Playgroud)

看法:

        <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"  >
Run Code Online (Sandbox Code Playgroud)

xaml.cs:

        public ACARSubLedgerUC(ACARSubLedgerVM vm)
    {
        InitializeComponent();
        DataContext = vm;
    }
Run Code Online (Sandbox Code Playgroud)

ksk*_*cou 3

你正在做的事情应该有效。

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

<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>
Run Code Online (Sandbox Code Playgroud)

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