你有沒有考慮覆蓋在你的綁定對象Equals方法? 這將工作;)
你也可以添加一個SelectedValue屬性到視圖模型,並添加SelectedValuePath和SelectedValue與TwoWay綁定到您的視圖。 這裏有一個簡單的例子: 查看:
<UserControl.Resources>
<SilverlightApplication2:TestCollection x:Key="TestCollection" />
<SilverlightApplication2:TestSelectedItem x:Key="TestSelectedItem"/>
</UserControl.Resources>
<Grid
x:Name="LayoutRoot"
Background="White">
<ComboBox
DisplayMemberPath="Text"
SelectedValuePath="Id"
SelectedValue="{Binding SelectedValue, Source={StaticResource TestSelectedItem}, Mode=TwoWay}"
Height="25"
DataContext="{StaticResource TestCollection}"
ItemsSource="{Binding Tests}"
SelectedItem="{Binding SelectedItem}"/>
</Grid>
快速和骯髒的背後代碼;)
public class Test
{
public int Id { get; set; }
public string Text { get; set; }
}
public class TestCollection
{
public ObservableCollection<Test> Tests { get; set; }
public TestCollection()
{
this.Tests = new ObservableCollection<Test>();
Tests.Add(new Test{ Id = 1, Text = "one"});
Tests.Add(new Test { Id = 2, Text = "two" });
Tests.Add(new Test { Id = 3, Text = "three" });
}
}
public class TestSelectedItem
{
public Test SelectedItem { get; set; }
private int _selectedValue;
public int SelectedValue
{
get { return _selectedValue; }
set { _selectedValue = value; }
}
public TestSelectedItem()
{
SelectedItem = new Test {Id = 2, Text = "two"};
SelectedValue = 2;
}
}
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
}
希望這有助於。
BR,
TJ
我第一次嘗試平等的覆蓋,但似乎並沒有工作。設置SelectedValuePath和的SelectedValue做的工作。 – 2011-03-23 15:34:16