sammarcow
sammarcow

Reputation: 2956

WPF ComboBox not Firing on selection

I have a ComboBox, shown below. Why isn't the code-behind always firing?

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

Upvotes: 0

Views: 214

Answers (1)

Haspemulator
Haspemulator

Reputation: 11308

I'll post my working code here, it's very simple. I've just created a default WPF app using VS2012 template. Here's MainWindow.xaml content:

<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>

Here's code-behind:

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();
        }
    }
}

When I select different values in combo-box, the TextBlock updates to the same value, hence the VM's property is also updated.

Upvotes: 1

Related Questions