使用Grid DataContext设置WPF ComboBox

时间:2015-04-26 07:47:48

标签: c# wpf combobox

我是DataContext的新手,我想将combobox设置为<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> 我的xml位于下方

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

有人可以指导我如何通过设置网格DataContext而不是手动设置combobox来设置//DB CONNECTION $sql = "SELECT * FROM `slevy` WHERE 1 "; $result = $conn->query($sql); while ($row = $result->fetch_assoc()) { $sleva = $row['sleva']; echo $sleva; } echo "------------".$sleva;

1 个答案:

答案 0 :(得分:1)

而不是

SelectedValuePath="CategoriesVal" SelectedValue="{Binding Categories}"

SelectedItem="{Binding CategoriesVal}"

SelectedValuePath表示:属性的名称(来自ComboBoxItem DataContex - Categories类(在我们的例子中),将提供SelectedValue的值。
 如果您想要表示实例项(每个表单Combobox.Items)不是由项目本身完成,而是由一个特征完成,这非常有用。在你的情况下,我没有看到任何意义。

了解详情:Difference between SelectedItem, SelectedValue and SelectedValuePath