WPF ComboBox忽略禁用的选定项目更新

时间:2018-06-22 08:15:07

标签: c# wpf combobox

使用以下代码,我希望组合框恢复为初始的Selected_Item,但事实并非如此,窗口上的ComboBox始终显示我选择的任何新项目(并且与模型不同步),我也尝试过总是调用OnPropertyChanged(“ Selected_Item”);无论值是否不同,组合框仍会显示新选择的项目,并且会不同步。可能是我做错了方法,但是正确的方法是什么?

namespace WpfApplication8
{
    public class Context : INotifyPropertyChanged
    {
        #region Privates

        bool c_Disabled = false;

        #endregion

        #region Ctors

        public Context()
        {
            Items = new List<MyItem>();

            Items.Add(new MyItem("Item 1"));
            Items.Add(new MyItem("Item 2"));
            Items.Add(new MyItem("Item 3"));

            Selected_Item = Items[0];

            c_Disabled = true;
        }

        #endregion

        #region Properties

        public List<MyItem> Items
        {
            get;
            private set;
        }

        private MyItem c_Selected_Item;
        public MyItem Selected_Item
        {
            get { return c_Selected_Item; }
            set
            {
                if (c_Selected_Item != value)
                {
                    if (!c_Disabled)
                    {
                        c_Selected_Item = value;

                        OnPropertyChanged("Selected_Item");
                    }

                }
            }
        }


        #endregion

        #region INotifyPropertyChanged implementation

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string f_Prop_Name)
        {
            PropertyChangedEventHandler l_Handler = PropertyChanged;
            if(null != l_Handler)
            {
                l_Handler(this, new PropertyChangedEventArgs(f_Prop_Name));
            }
        }

        #endregion
    }

    public class MyItem
    {
        public MyItem(string f_Name)
        {
            Name = f_Name;
        }

        public string Name {get;set;}
    }
}

和以下窗口:

<Window x:Class="WpfApplication8.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ComboBox
            HorizontalAlignment="Center"
            VerticalAlignment="Top"
            ItemsSource="{Binding Items}"
            SelectedItem="{Binding Selected_Item}">

            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}"/>
                </DataTemplate>
            </ComboBox.ItemTemplate>

        </ComboBox>
    </Grid>
</Window>

1 个答案:

答案 0 :(得分:-1)

从Context方法中删除c_Disabled = true;