0

我有一个 ComboBox,如下所示。为什么代码隐藏不总是触发?

XAML:

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

代码隐藏:

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;
    }
}
4

1 回答 1

1

我将在这里发布我的工作代码,它非常简单。我刚刚使用 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 的属性也会更新。

于 2013-02-15T22:33:55.127 回答