WPF ComboBox在选择时没有触发

时间:2013-02-15 21:01:25

标签: wpf mvvm binding

我有一个ComboBox,如下所示。为什么代码隐藏总是不会被解雇?

XAML:

<ComboBox   Height="23"
                        Name="cbAppendCreate"
                        VerticalAlignment="Top"
                        Width="120"
                        Margin="{StaticResource ConsistentMargins}"
                        ItemsSource="{Binding Path=CbCreateAppendItems}"
                        SelectedValue="{Binding Path=CbAppendCreate,UpdateSourceTrigger=PropertyChanged}" />

CodeBehind:

private string cbAppendCreate;
public string CbAppendCreate {
    get {
        //....
        return cbAppendCreate
    }
    set { //This doesn't fire when selecting the first of 2 Items, 
          //but always fires when selecting the 2nd of two items 
          //....
         cbAppendCreate = value;
    }
}

1 个答案:

答案 0 :(得分:0)

我会在这里发布我的工作代码,这很简单。我刚刚使用VS2012模板创建了一个默认的WPF应用程序。这是MainWindow.xaml内容:

<Window x:Class="
    WpfApplication1.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">
<StackPanel>
    <ComboBox   Height="23"
                    Name="cbAppendCreate"
                    VerticalAlignment="Top"
                    Width="120"
                    ItemsSource="{Binding Path=CbCreateAppendItems}"
                    SelectedValue="{Binding Path=CbAppendCreate,UpdateSourceTrigger=PropertyChanged}" />
    <TextBlock Text="{Binding CbAppendCreate}"></TextBlock>
</StackPanel>

这是代码隐藏:

namespace WpfApplication1
    {
    public class DataSource
    {
        public List<string> CbCreateAppendItems { get; set; }
        public string CbAppendCreate { get; set; }
        public DataSource()
        {
            CbCreateAppendItems = new List<string>() { "create", "append" };
        }
    }
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new DataSource();
        }
    }
}

当我在组合框中选择不同的值时,TextBlock会更新为相同的值,因此VM的属性也会更新。