Skip to main content
 首页 » 编程设计

c#之WPF 选择值,显示成员路径与列表框和组合框不一致

2024年02月23日14bluestorm

我有一个名为 DropDownIndividuals() 的存储过程,它是使用 LINQ 创建的。 存储过程返回 FullName 和 Case_Number。我想在我的存储过程中将 SelectedValuePath 设置为等于 Case_Number 列。这就是我为列表框所做的并且它有效。

private void listBox1_Loaded(object sender, RoutedEventArgs e){ 
    using (ToolboxDataContext toolboxDB = new ToolboxDataContext())//this is linq in action 
    { 
         var x = toolboxDB.DropDownIndividuals().ToList();//convert to a list 
         listBox1.ItemsSource = x;  //bind the data  
         listBox1.SelectedValuePath = "Case_Number"; 
         listBox1.DisplayMemberPath = "FullName"; 
 
         Console.WriteLine(listBox1.SelectedValue.ToString()); 
         //Result:it shows the case number of the person the user picks. 
    } 
} 

现在我对下拉组合框做了同样的事情,但它不起作用。

private void individualDropDown_Loaded(object sender, RoutedEventArgs e) 
{ 
    using (ToolboxDataContext toolbox = new ToolboxDataContext()) 
    { 
        var individualDropDownBox = toolbox.DropDownIndividuals().ToList(); 
        individualDropDown.ItemsSource = individualDropDownBox; 
        individualDropDown.DisplayMemberPath = "FullName"; 
        individualDropDown.SelectedValuePath = "Case_Number"; 
        Console.WriteLine(individualDropDown.SelectedValue.ToString()); 
    } 
} 

为什么?我该如何解决这个问题?

请您参考如下方法:

为什么这么乱?您甚至不需要以相同的顺序设置属性,这 是等价的:

<Grid Margin="5"> 
    <Grid.ColumnDefinitions> 
        <ColumnDefinition/> 
        <ColumnDefinition/> 
    </Grid.ColumnDefinitions> 
    <Grid.RowDefinitions> 
        <RowDefinition/> 
        <RowDefinition Height="Auto"/> 
    </Grid.RowDefinitions> 
    <ListBox Grid.Row="0" Grid.Column="0" 
             Name="lbData" ItemsSource="{Binding DpData}" 
             DisplayMemberPath="Name" 
             SelectedValuePath="Id"/> 
    <TextBlock Grid.Row="1" Grid.Column="0" 
               Text="{Binding ElementName=lbData, Path=SelectedValue}"/> 
 
    <ComboBox Grid.Row="0" Grid.Column="1" VerticalAlignment="Top" 
              Name="cbData" ItemsSource="{Binding DpData}" 
              DisplayMemberPath="Name" 
              SelectedValuePath="Id"/> 
    <TextBlock Grid.Row="1" Grid.Column="1" 
               Text="{Binding ElementName=cbData, Path=SelectedValue}"/> 
</Grid> 

...它显示与预期相同的 ID。

编辑:顺便说一下,在启动时,两个控件的选定值都是null。