我是C# WPF的新手,我正在尝试将DataContext设置为combobox,我的xml如下所示
<Grid Name="groupEditArea" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="#FFD8D8D8" Margin="-14,0,192,0">
<Label Content="Group Name" FontSize="18" HorizontalAlignment="Left" Margin="116,50,0,0" VerticalAlignment="Top" Width="136"/>
<Label Content="Group Type" FontSize="18" HorizontalAlignment="Left" Margin="116,123,0,0" VerticalAlignment="Top" Width="136"/>
<TextBox x:Name="groupGroupNameTxt" HorizontalAlignment="Left" FontSize="16" Height="31" Margin="368,50,0,0" TextWrapping="Wrap" Text="{Binding Path = GroupName, Mode=TwoWay, StringFormat=\{0:n3\}, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="226" TextChanged="groupGroupNameTxt_TextChanged" /> <!-- GotFocus="GroupGroupNameTxt_OnGotFocus" TextInput="GroupGroupNameTxt_OnTextInput" -->
<ComboBox x:Name="groupGroupNameCombo" HorizontalAlignment="Left" Margin="368,123,0,0" VerticalAlignment="Top" Width="226" Height="31" SelectionChanged="groupGroupNameCombo_SelectionChanged" DisplayMemberPath="GroupName" SelectedValuePath="CategoriesVal" SelectedValue="{Binding Categories}"/>
</Grid>我的POCO如下:-
public class Test: INotifyPropertyChanged
{
public Test()
{
}
public virtual string TestId { get; set; }
public virtual Categories CategoriesVal { get; set; }
public virtual string Name{ get; set; }
public virtual string GroupName
{
get { return Name; }
set
{
Name = value;
OnPropertyChanged("GroupName");
}
}
}
public class Categories : INotifyPropertyChanged
{
public Categories ()
{
}
public virtual string CategorieId { get; set; }
public virtual string Name{ get; set; }
public virtual string GroupName
{
get { return Name; }
set
{
Name = value;
OnPropertyChanged("GroupName");
}
}
}
}在我的backend代码中,我将DataContext设置为:-
Categories cate = new Categories ();
cate.CategorieId = "cate1ID";
cate.GroupName = "CateGroupName1"
Test test = new Test();
test.TestId = "TestID";
test.CategoriesVal = cate;
test.Name = "TestName1";而groupGroupNameCombo是使用ItemsSource设置的,当我在Categories上设置的时候,它包含了整个列表。
groupGroupNameCombo.SelectedItem = cate;但是,当我开始使用下面的网格时,它将无法工作:-
groupEditArea.DataContext = test;有人能指导我如何通过设置网格combobox而不是手动设置combobox来设置combobox。
发布于 2015-04-26 09:32:52
相反,
SelectedValuePath="CategoriesVal" SelectedValue="{Binding Categories}"写
SelectedItem="{Binding CategoriesVal}"SelectedValuePath的意思是:属性的名称(在本例中来自ComboBoxItem DataContex - Categories类),其中将提供SelectedValue的值。
如果您希望表示实例项(每个表单Combobox.Items)不是由项本身完成的,而是由一个特性完成的,这是非常有用的。在你的情况下,我看不出有什么意义。
见更多信息:Difference between SelectedItem, SelectedValue and SelectedValuePath
https://stackoverflow.com/questions/29875084
复制相似问题