2016-11-24 60 views
0

我從數據庫拉項目到一個列表框,它由幾列組成。我想刪除按鈕添加到我的DB拉每個項目,但我似乎無法轉發該項目的ID,它總是說0WPF棱鏡列表框按鈕

<ListBox ItemsSource="{Binding LbPlugins}" HorizontalContentAlignment="Stretch" Grid.Row="1"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <Grid HorizontalAlignment="Stretch"> 
       <Grid.ColumnDefinitions> 
        <ColumnDefinition Width="5*"/> 
        <ColumnDefinition Width="5*"/> 
        <ColumnDefinition Width="*"/> 
        <ColumnDefinition Width="*"/> 
       </Grid.ColumnDefinitions> 

       <CheckBox Grid.Column="0" Content="{Binding Name}" IsChecked="{Binding IsActive}"/> 
       <Label Grid.Column="1" Content="{Binding ClassName}"/> 
       <Button Grid.Column="2" Content="E" Command="{Binding btnEditPluginCommand}"/> 
       <Button Grid.Column="3" Content="D" Command="{Binding Path=DataContext.btnDeletePluginCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" CommandParameter="{Binding PluginId}"/> 

      </Grid> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

在視圖模型:

private int pluginId; 
    public int PluginId 
    { 
     get { return pluginId; } 
     set { SetProperty(ref pluginId, value); } 
    } 
    public DelegateCommand btnDeletePluginCommand { get; set; } 

...

在構造

btnDeletePluginCommand = new DelegateCommand(DeletePlugin); 

...

private void DeletePlugin() 
{ 
    var result = MessageBox.Show("Are you sure you want to delete this plugin?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); 
    if (result == DialogResult.Yes) 
    { 
     MessageBox.Show("YAY, ID=" + pluginId); 
    } 
} 

回答

1

當你使用棱鏡你應該使用DelegateCommand,即Prism的ICommand實現。

爲了使這項工作,您需要使用一個對象或可空類型作爲通用CommandDelegate的參數。如果你沒有做到這一點,你會在運行時得到一個InvalidCastException

聲明你的命令是這樣的:

public ICommand btnDeletePluginCommand { get; set; } 

初始化它視圖模型的構造:

btnDeletePluginCommand = new DelegateCommand<int?>(DeletePlugin); 

並重構你的方法:

private void DeletePlugin(int? pluginId) 
{ 
    if (pluginId == null) return; 

    var result = MessageBox.Show("Are you sure you want to delete this plugin?", "", MessageBoxButtons.YesNo, 
     MessageBoxIcon.Warning); 
    if (result == DialogResult.Yes) 
     MessageBox.Show("YAY, ID=" + pluginId); 
} 

正如您將命令綁定到ListBox一樣,pluginId參數永遠不會爲null,但您應該始終驗證。也許你在其他UI組件中使用這個視圖模型?

順便說一句,你不應該在視圖模型中使用MessageBox。我想這是一個概念證明或什麼的:)。在MVVM的情況下,您應該注入一個DialogService或使用InteractionRequests來顯示來自您的視圖模型的通知。

希望這會有所幫助!

0

既然你已經通過XAML中的參數,你可以使用:

btnDeletePluginCommand = new Microsoft.Practices.Prism.Commands.DelegateCommand<int>(DeletePlugin); 

然後你DeletePlugin應該有一個參數是這樣的:

private void DeletePlugin(int pluginId) 
{ 
    ... 
}