Ho un problema durante il tentativo di associare 2 o più Combobox SelectedValue a una proprietà, ovvero null. Solo 1 delle caselle combinate associate a questa proprietà mostrerà il valore reale.WPF ComboBox SelectedValue binding con valore null viene visualizzato vuoto
Di seguito è il mio Xaml in cui utilizzo DataTemplate per selezionare un Combobox per la presentazione di viewModel.
Xaml:
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Test"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate DataType="{x:Type local:PropertyValueViewModel}">
<ComboBox SelectedValue="{Binding Value}" ItemsSource="{Binding SelectableValues}" DisplayMemberPath="Description" SelectedValuePath="Value"/>
</DataTemplate>
</Window.Resources>
<StackPanel>
<Label Content="These uses template:"></Label>
<ContentPresenter Content="{Binding ValueSelector}"></ContentPresenter>
<ContentPresenter Content="{Binding ValueSelector}"></ContentPresenter>
<ContentPresenter Content="{Binding ValueSelector}"></ContentPresenter>
</StackPanel>
E il codice dietro:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ValueSelector = new PropertyValueViewModel()
{
SelectableValues = new List<SelectableValue>()
{
new SelectableValue("NULL", null),
new SelectableValue("1", 1)
},
Value = null
};
DataContext = this;
}
public static readonly DependencyProperty ValueSelectorProperty = DependencyProperty.Register(
"ValueSelector", typeof(PropertyValueViewModel), typeof(MainWindow), new PropertyMetadata(default(PropertyValueViewModel)));
public PropertyValueViewModel ValueSelector
{
get { return (PropertyValueViewModel)GetValue(ValueSelectorProperty); }
set { SetValue(ValueSelectorProperty, value); }
}
}
/// <summary>
/// My viewModel
/// </summary>
public class PropertyValueViewModel
{
public object Value { get; set; }
public object SelectableValues { get; set; }
}
/// <summary>
/// The items in the combobox
/// </summary>
public class SelectableValue
{
public SelectableValue(string header, object value)
{
Value = value;
Description = header;
}
public object Value { get; set; }
public string Description { get; set; }
}
Ora mi chiedo perché solo 1 di loro possono mostrare il valore NULL all'avvio? Posso cambiare il valore in ognuno di essi e si sincronizzeranno tutti con il valore nella proprietà - se seleziono 1 e poi torno a NULL, tutti mostreranno NULL. Sembra che solo il valore iniziale non sia mostrato correttamente.
Se evito di utilizzare DataTemplate, funziona anche il binding. Qualcuno sa perché il DAtaTemplate si comporta in questo modo?
Grazie. Segnalo come soluzione, poiché ha un paio di modi per risolvere il problema e una buona spiegazione del problema. – Patrick