Silverlight ComboBox SelectedValue TwoWay绑定不起作用

时间:2013-07-26 05:29:11

标签: c# .net silverlight-4.0

我在我的应用程序中使用了很多ComboBox,所有这些都没有任何问题。但是,我现在找不到问题。我已将SelectedValuePath设置为“Tag”属性。但是更改ComboBox选定项后属性不会更新。我已阅读其他StackOverflow问题,但仍未提供帮助。

是xaml:

  

的xmlns:虚拟机= “CLR-名称空间:SilverlightApplication1”

<UserControl.DataContext>
    <vms:MainViewModel />
</UserControl.DataContext>

<Grid x:Name="LayoutRoot" Background="White">
    <ComboBox Width="100" VerticalAlignment="Center" FontFamily="Segoe UI"
         Height="30" Margin="0,5,0,0"  HorizontalAlignment="Left" 
         SelectedValue="{Binding SelectedDifStatusComparer, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
         SelectedValuePath="Tag">
        <ComboBox.Items>
            <ComboBoxItem Tag="H" >High</ComboBoxItem>
            <ComboBoxItem Tag="L" >Low</ComboBoxItem>
            <ComboBoxItem Tag="E" >Equal</ComboBoxItem>
        </ComboBox.Items>
    </ComboBox>
</Grid>

这是ViewModel:

public class MainViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        private string _selectedDifStatusComparer = "";
        private string SelectedDifStatusComparer
        {
            get { return _selectedDifStatusComparer; }
            set
            {
                _selectedDifStatusComparer = value;
                MessageBox.Show(_selectedDifStatusComparer);
                OnPropertyChanged("SelectedDifStatusComparer");
            }
        }

        public MainViewModel()
        {
            SelectedDifStatusComparer = "E"; // It is working, the MessageBox is apperaing
        }
    }

2 个答案:

答案 0 :(得分:2)

您的财产是私人的。将其更改为公开,它应该有效。

 public class MainViewModel : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            private void OnPropertyChanged(string propertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }

            private string _selectedDifStatusComparer = "";
            public string SelectedDifStatusComparer
            {
                get { return _selectedDifStatusComparer; }
                set
                {
                    _selectedDifStatusComparer = value;
                    MessageBox.Show(_selectedDifStatusComparer);
                    OnPropertyChanged("SelectedDifStatusComparer");
                }
            }

            public MainViewModel()
            {
                SelectedDifStatusComparer = "E"; // It is working, the MessageBox is apperaing
            }
        }

答案 1 :(得分:1)

您的财产是私人的。将其更改为公开,它应该有效。