在INotifyPropertyChanged上调用IValueConverter仅在启动时有效

时间:2018-08-22 15:10:29

标签: c# wpf xaml inotifypropertychanged ivalueconverter

我试图根据枚举的值更改PDF中可见的网格。枚举本身的值基于菜单,并且在选择菜单选项时,枚举值会更改并调用PropertyChangedEventHandler。

包含PropertyChangedEventHandler的类的代码如下:

public class ScreenToShow : INotifyPropertyChanged
{
    public enum MenuState { MenuPage, MenuChoice1, MenuChoice2, MenuChoice3};

    MenuState state;

    public MenuState _State
    {
        get { return state; }
        set
        {
            state = value;
            this.NotifyPropertyChanged("_State");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string propName)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
    }
}

要更改我的WPF窗口的内容,我将4个网格的可见性(每个为菜单的一个选项+起始页)绑定到此转换器,如下所示: 资源:

<Window.Resources>
    <local:ScreenToShow x:Key="myScreenToShow"></local:ScreenToShow>
    <local:VisibilityScreenConverter x:Key="myVisibilityScreenConverter"></local:VisibilityScreenConverter>
</Window.Resources>

四个网格之一的XAML代码:

<Grid DataContext="{Binding Source={StaticResource myScreenToShow}}" Name="MenuPage" Grid.Row="1" Visibility="{Binding Path= _State, Converter={StaticResource myVisibilityScreenConverter}, ConverterParameter='menuPage', UpdateSourceTrigger=Default, Mode=TwoWay}">

转换器的代码如下:

  class VisibilityScreenConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is ScreenToShow.State)
            {
                if((string)parameter == "menuPage")
                {
                    switch(value)
                    {
                        case ScreenToShow.State.MenuPage:
                            return Visibility.Visible;
                        default:
                            return Visibility.Hidden;
                    }
                }
                else if ((string)parameter == "menuChoice1")
                {
                    switch (value)
                    {
                        case ScreenToShow.State.MenuChoice1:
                            return Visibility.Visible;
                        default:
                            return Visibility.Hidden;
                    }
                }
                else if ((string)parameter == "menuChoice2")
                {
                    switch (value)
                    {
                        case ScreenToShow.State.MenuChoice2:
                            return Visibility.Visible;
                        default:
                            return Visibility.Hidden;
                    }
                }
                else // Menu choice 3
                {
                    switch (value)
                    {
                        case ScreenToShow.State.MenuChoice3:
                            return Visibility.Visible;
                        default:
                            return Visibility.Hidden;
                    }
                }
            }
            else
            {
                return Visibility.Visible;
            }
        }

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

在MainWindow.cs中,使用以下代码:

    ScreenToShow screenToShowEnum = new ScreenToShow();

    public MainWindow()
    {
        DataContext = this;
        InitializeComponent();
        screenToShowEnum._State =  ScreenToShow.State.MenuPage;
    }

    private void MenuChoice1_Click(object sender, RoutedEventArgs e)
    {
        screenToShowEnum._State = ScreenToShow.State.MenuChoice1;
    }

    private void MenuChoice2_Click(object sender, RoutedEventArgs e)
    {
        screenToShowEnum._State = ScreenToShow.State.MenuChoice2;
    }

private void MenuChoice3_Click(object sender, RoutedEventArgs e)
        {
            screenToShowEnum._State = ScreenToShow.State.MenuChoice3;
        }

在启动时,代码可以正常工作,并且同时调用NotifyPropertyChanged和Converter(通过console.writeline对其进行了检查)。此外,可以按预期处理不同网格的可见性。 选择菜单选项之一时,也会按预期方式调用PropertyChangedHandler。但是,不同网格的可见性不会改变。 可见性在启动时根据我的代码而改变,但在以后的阶段中更改枚举的值时却没有改变,这是我做错了吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

问题是您要引用两个完全不同的ViewModel对象,一个对象由您的xaml视图使用,另一个对象由文件后面的代码使用。

要么在文件后面的代码中设置DataContext属性,要么通过以下命令在xaml文件中进行设置:

<Window.DataContext>
    <StaticResource ResourceKey="myScreenToShow" />
</Window.DataContext>

如果您使用第二种方法,请确保在事件处理程序中强制转换并使用DataContext

private void MenuChoice1_Click(object sender, RoutedEventArgs e)
{
    (DataContext as ScreenToShow)._State = ScreenToShow.MenuState.MenuChoice1;
}

private void MenuChoice2_Click(object sender, RoutedEventArgs e)
{
    (DataContext as ScreenToShow)._State = ScreenToShow.MenuState.MenuChoice2;
}

private void MenuChoice3_Click(object sender, RoutedEventArgs e)
{
    (DataContext as ScreenToShow)._State = ScreenToShow.MenuState.MenuChoice3;
}

演示代码:

<Window
        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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplicationTest"
        xmlns:Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero2" x:Class="WpfApplicationTest.MainWindow"
        mc:Ignorable="d"
        x:Name="win"
        WindowStartupLocation="CenterOwner"
        Title="MainWindow" Height="300" Width="300">
    <Window.Resources>
        <ResourceDictionary>
            <local:ScreenToShow x:Key="myScreenToShow"></local:ScreenToShow>
            <local:VisibilityScreenConverter x:Key="myVisibilityScreenConverter"></local:VisibilityScreenConverter>
        </ResourceDictionary>
    </Window.Resources>
    <Window.DataContext>
        <StaticResource ResourceKey="myScreenToShow" />
    </Window.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal">
            <Button Margin="5" Content="Menu 1" Click="MenuChoice1_Click" />
            <Button Margin="5" Content="Menu 2" Click="MenuChoice2_Click" />
            <Button Margin="5" Content="Menu 3" Click="MenuChoice3_Click" />
        </StackPanel>

        <Grid DataContext="{Binding Source={StaticResource myScreenToShow}}"
              Name="MenuPage1"
              Grid.Row="1"
              Visibility="{Binding Path= _State, Converter={StaticResource myVisibilityScreenConverter}, ConverterParameter='menuChoice1', UpdateSourceTrigger=Default, Mode=TwoWay}">
            <TextBlock Text="Menu 1" FontSize="24" />
        </Grid>
        <Grid DataContext="{Binding Source={StaticResource myScreenToShow}}"
              Name="MenuPage2"
              Grid.Row="1"
              Visibility="{Binding Path= _State, Converter={StaticResource myVisibilityScreenConverter}, ConverterParameter='menuChoice2', UpdateSourceTrigger=Default, Mode=TwoWay}">
            <TextBlock Text="Menu 2" FontSize="24" />
        </Grid>
        <Grid DataContext="{Binding Source={StaticResource myScreenToShow}}"
              Name="MenuPage3"
              Grid.Row="1"
              Visibility="{Binding Path= _State, Converter={StaticResource myVisibilityScreenConverter}, ConverterParameter='menuChoice3', UpdateSourceTrigger=Default, Mode=TwoWay}">
            <TextBlock Text="Menu 3" FontSize="24" />
        </Grid>
    </Grid>
</Window>

文件背后的代码:

class VisibilityScreenConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is ScreenToShow.MenuState)
        {
            var state = (ScreenToShow.MenuState)value;
            if ((string)parameter == "menuPage")
            {
                switch (state)
                {
                    case ScreenToShow.MenuState.MenuPage:
                        return Visibility.Visible;
                    default:
                        return Visibility.Hidden;
                }
            }
            else if ((string)parameter == "menuChoice1")
            {
                switch (state)
                {
                    case ScreenToShow.MenuState.MenuChoice1:
                        return Visibility.Visible;
                    default:
                        return Visibility.Hidden;
                }
            }
            else if ((string)parameter == "menuChoice2")
            {
                switch (state)
                {
                    case ScreenToShow.MenuState.MenuChoice2:
                        return Visibility.Visible;
                    default:
                        return Visibility.Hidden;
                }
            }
            else // Menu choice 3
            {
                switch (state)
                {
                    case ScreenToShow.MenuState.MenuChoice3:
                        return Visibility.Visible;
                    default:
                        return Visibility.Hidden;
                }
            }
        }
        else
        {
            return Visibility.Visible;
        }
    }

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

public class ScreenToShow : INotifyPropertyChanged
{
    public enum MenuState { MenuPage, MenuChoice1, MenuChoice2, MenuChoice3 };

    MenuState state;

    public MenuState _State
    {
        get { return state; }
        set
        {
            state = value;
            this.NotifyPropertyChanged("_State");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string propName)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
    }
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void MenuChoice1_Click(object sender, RoutedEventArgs e)
    {
        (DataContext as ScreenToShow)._State = ScreenToShow.MenuState.MenuChoice1;
    }

    private void MenuChoice2_Click(object sender, RoutedEventArgs e)
    {
        (DataContext as ScreenToShow)._State = ScreenToShow.MenuState.MenuChoice2;
    }

    private void MenuChoice3_Click(object sender, RoutedEventArgs e)
    {
        (DataContext as ScreenToShow)._State = ScreenToShow.MenuState.MenuChoice3;
    }
}