I have a not editable ComboBox to display all tables of and SQL Database.
<ComboBox Grid.Column="1"
Grid.Row="2"
Height="23"
Margin="3,3,3,3" Name="cbLogTable" VerticalAlignment="Top"
ItemsSource="{Binding}"
TextSearch.TextPath="TABLE_NAME"
SelectedValue="{Binding Path=LogTable, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, ValidatesOnDataErrors=True}"
>
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=TABLE_NAME}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
The property of the containing UserControl looks like this and also implements the INotifyPropertyChanged:
public string LogTable
{
get
{
return _logTable;
}
set
{
if (_logTable == value) return;
_logTable = value;
OnPropertyChanged("LogTable");
}
}
I use the following data binding to fill the ComboBox:
private void UpdateLogTable()
{
var connection = new SqlConnection(_connectionString);
connection.Open();
DataTable t = connection.GetSchema("Tables");
cbLogTable.DataContext = t;
connection.Close();
}
But I don't receive a PropertyChanged notification on changing the selected value of the ComboBox. Where is my fault?
In the binding of SelectedValue
:
SelectedValue="{Binding Path=LogTable,
UpdateSourceTrigger=PropertyChanged,
Mode=TwoWay,
ValidatesOnDataErrors=True,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type UserControl}}}"
Otherwise, the binding is looking for LogTable
property on the DataTable
type (which is the DataContext for the Combobox), and fails silently.