我設法建立一個自定義列表框,其中每個項目從一個數據庫中加載顯示在一個堆棧面板中的名稱和姓氏。在這兩個文本框之後,應該有一個按鈕,該按鈕正確綁定到ViewModel的ICommand。 按鈕正確調用正確的方法,但不會刪除selectedPerson,因爲該對象爲空。WPF自定義列表框selectdItem與按鈕
這是列表框
<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>
這是在視圖模型
private void DeletePatient()
{
patientsManager.DeletePatient(SelectedPatient);
ListOfPatients = new ObservableCollection<RealPatient>(patientsManager.GetAllRealPatients());
SelectedPatient = null;
}
相關方法的WPF這是自定義列表框如何被包含在查看
<ListBox Grid.Row="2" Grid.Column="3" Style="{StaticResource CustomHorizontalListbox}" ItemsSource="{Binding ListOfPatients}" SelectedItem="{Binding SelectedPatient}">
</ListBox>
所以問題在於DeleteMethod中的斷點顯示SelectedPatient = null ..
我怎麼錯過......甚至當我的列表中的項目,而不是單一的按鈕點擊SelectedPatient不會改變
感謝
嘗試增加'模式= TwoWay'和'UpdateSourceTrigger = PropertyChanged'到您的SelectedItem綁定。 –
沒有...它不工作... –
試試我的解決方案,它工作正常,我.. –