为什么在下面的例子中,组合框设置为空而不是“先生”?如何设置XAML Combobox的选定值?
XAML:
<Window x:Class="TestComb82822.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel HorizontalAlignment="Left">
<ComboBox SelectedValue="{Binding Salutation}" Width="200">
<ComboBoxItem>Company</ComboBoxItem>
<ComboBoxItem>Ms.</ComboBoxItem>
<ComboBoxItem>Mr.</ComboBoxItem>
</ComboBox>
</StackPanel>
</Window>
后面的代码:
using System.Windows;
using System.ComponentModel;
namespace TestComb82822
{
public partial class Window1 : Window, INotifyPropertyChanged
{
#region ViewModelProperty: Salutation
private string _salutation;
public string Salutation
{
get
{
return _salutation;
}
set
{
_salutation = value;
OnPropertyChanged("Salutation");
}
}
#endregion
public Window1()
{
InitializeComponent();
DataContext = this;
Salutation = "Mr.";
}
#region INotifiedProperty Block
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
第二个尝试:
布莱恩的SelectedItem和WindowLoaded也不管用,这仍使组合框空白:
XAML:
<Window x:Class="TestCombo234.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel HorizontalAlignment="Left">
<ComboBox SelectedItem="{Binding Salutation}" Width="200">
<ComboBoxItem>Company</ComboBoxItem>
<ComboBoxItem>Ms.</ComboBoxItem>
<ComboBoxItem>Mr.</ComboBoxItem>
</ComboBox>
</StackPanel>
</Window>
代码背后:
using System.Windows;
using System.ComponentModel;
namespace TestCombo234
{
public partial class Window1 : Window, INotifyPropertyChanged
{
#region ViewModelProperty: Salutation
private string _salutation;
public string Salutation
{
get
{
return _salutation;
}
set
{
_salutation = value;
OnPropertyChanged("Salutation");
}
}
#endregion
public Window1()
{
InitializeComponent();
DataContext = this;
Loaded += new RoutedEventHandler(Window1_Loaded);
}
void Window1_Loaded(object sender, RoutedEventArgs e)
{
Salutation = "Mr.";
}
#region INotifiedProperty Block
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
即使称呼= “先生”是在InitializeComponent之前,组合框仍然是空的:-( – 2009-10-20 13:10:58
@爱德华:也许尝试在XAML中尝试绑定'SelectedItem'而不是'SelectedValue'? – Noldorin 2009-10-20 13:35:13
谢谢但SelectedItem仍然使组合框空白 – 2009-10-20 13:47:37