【发布时间】:2013-03-23 20:35:47
【问题描述】:
我设法构建了一个自定义列表框,其中每个项目都从数据库中加载,在堆栈面板中显示名称和姓氏。在这 2 个文本框之后应该有一个按钮,它正确绑定到 ViewModel 的 ICommand。 该按钮正确调用了正确的方法,但它不会删除 selectedPerson,因为该对象为空。
这是列表框的 WPF
<Style x:Key="CustomHorizontalListbox" TargetType="{x:Type ListBox}">
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="2">
<StackPanel Orientation="Horizontal" Width="200" Margin="0,0,0,0">
<TextBox Text="{Binding FirstName}" Width="60" BorderThickness="0" Margin="0" IsReadOnly="True"></TextBox>
<TextBox Text="{Binding LastName}" Width="100" BorderThickness="0" Margin="0" IsReadOnly="True"></TextBox>
<Button Width="20" Height="20" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}, Path=DataContext.OnDeletePatient}" CommandParameter="{Binding}"></Button>
</StackPanel>
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<WrapPanel></WrapPanel>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>
这是 ViewModel 上的相对方法
private void DeletePatient()
{
patientsManager.DeletePatient(SelectedPatient);
ListOfPatients = new ObservableCollection<RealPatient>(patientsManager.GetAllRealPatients());
SelectedPatient = null;
}
这就是自定义列表框包含在视图中的方式
<ListBox Grid.Row="2" Grid.Column="3" Style="{StaticResource CustomHorizontalListbox}" ItemsSource="{Binding ListOfPatients}" SelectedItem="{Binding SelectedPatient}">
</ListBox>
所以问题是 DeleteMethod 处的断点显示 SelectedPatient = null..
我错过了什么?...即使我点击列表项而不是单个按钮,SelectedPatient 也不会改变
谢谢
【问题讨论】:
-
尝试将
Mode=TwoWay和UpdateSourceTrigger=PropertyChanged添加到您的 SelectedItem-Binding。 -
不...它不起作用...
-
试试我的解决方案,对我来说效果很好..
-
不行,还是不行……!!
-
我发布了我的整个工作示例应用程序。
标签: wpf data-binding listbox