Monday 9 September 2013

WPF ComboBox: Bind ItemsSource to List and Two-way Bind selected value to ViewModel Property?

WPF ComboBox: Bind ItemsSource to List and Two-way Bind selected value to
ViewModel Property?

This is my first go 'round with WPF bindings of this nature so I'm sure
I'm doing something silly.
Background / Setup
I have the following:
A ViewModel (MainWindowViewModel)
A bound Datacontext
in the Window definition, DataContext="{StaticResource MainWindowViewModel}"
In the viewmodel, a list:
readonly List<string> _sqlServerChoices = new List<string>{"DEV", "SPDEV",
"SPSQL", "SQL2008"};
A viewmodel property exposing the list:
public List<string> SqlServerChoices{get { return _sqlServerChoices; }}
A ComboBox for selecting the SQL Server
A property called "Settings" which is a custom type, UploaderSettings,
which has collections of database settings, sharepoint settings, etc.
A property called SqlServerHasBeenEntered, which is a boolean that returns
whether the
A text box that should be enabled or disabled based on whether a SQL
The Goal
I would like to have the choices for the items in the combobox (the
ItemsSource) to be set to the list of SQL Servers. This appears to work
fine.
I would like the selected element of the list to be a two-way binding to
the Settings.DatabaseSettings.SqlServer property on the ViewModel.
When this property is updated, I would like to fire OnPropertyChanged for
the SqlServerHasBeenEntered property.
I would like to have the text box enabled or disabled based on whether the
SqlServerHasBeenEntered property is true or false.
The Problem
The binding appears to be failing silently. I see the combo box items, but
when I select them, nothing is changing and it appears the
onpropertychanged event handler isn't being called.
The Code So Far
The ComboBox XAML definition:
<ComboBox Grid.Row="0" Grid.Column="1" VerticalAlignment="Center"
ItemsSource="{Binding SqlServerChoices}"
SelectedValue="{Binding
Settings.DatabaseSettings.SqlServer,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged }">
The Boolean value for whether or not the SQL Server field has text:
public bool SqlServerHasBeenEntered
{
get
{
return !String.IsNullOrEmpty(Settings.DatabaseSettings.SqlServer);
}
}
The Property changing handler:
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string
propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}

1 comment:

  1. Are you looking to make cash from your traffic with popunder advertisments?
    If so, have you tried using Clickadu?

    ReplyDelete