TwoWay Binding of a ComboBox to a static property

后端 未结 2 1065
南方客
南方客 2021-01-15 02:53

-------EDIT------

So, i figured that my code is correct and so are the code snippets from all of your answers. Thanks for that. My

相关标签:
2条回答
  • 2021-01-15 03:30

    Checked just in a sample project, works fine

    public class ViewModel
    {
        static ViewModel()
        {
            Items=new ObservableCollection<string>();
            SelectedItem = "222";
            Items.Add("111");
            Items.Add("222");
            Items.Add("333");
            Items.Add("444");
            Items.Add("555");
        }
        private static string _selectedItem;
        public static string SelectedItem
        {
            get { return _selectedItem; }
            set { _selectedItem = value;
                MessageBox.Show("Item " + value + " was selected");
            }
        }
    
        private static ObservableCollection<string> _items;
        public static ObservableCollection<string> Items
        {
            get { return _items; }
            set { _items = value; }
        }
    }
    

    and xaml

    <Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:my="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="200" Width="300">
    <Grid>
        <Grid.Resources>
            <my:ViewModel x:Key="viewM"/>
        </Grid.Resources>
        <ComboBox Height="23" HorizontalAlignment="Left" Margin="101,12,0,0" Name="comboBox1" VerticalAlignment="Top" Width="146" 
                   ItemsSource="{Binding Source={x:Static my:ViewModel.Items}, Mode=OneWay}"
                  SelectedItem="{Binding Source={StaticResource viewM}, Path=SelectedItem}" />
        </Grid>
    </Window>
    

    I have uploaded sample.

    0 讨论(0)
  • 2021-01-15 03:33

    You're being confused between instances and static properties: you don't need to bind a static object.

    <ComboBox
            ItemsSource="{x:Static me:MainWindowViewModel.MyElements}"
            SelectedItem="{x:Static me:MainWindowViewModel.SelectedElement}" />
    

    And you should implement INotifyPropertyChanged nevertheless.

    Binding is about resolving the right instance from which you want to fetch data.
    If there is no meaning of instance, there is no need for binding.

    0 讨论(0)
提交回复
热议问题