2013-10-05 53 views
0

我如何在UserView中使用DelegateCommand在我的Lisview中?在我的列表視圖我使用它這樣:DelegateCommand與用戶控件列表視圖

<ListView x:Name="peopleListBox"> 

       <ListView.ItemTemplate> 
       <DataTemplate> 
        <Grid> 
          <UserControls:ItemTemplateControl QuestionText="{Binding parametr}"/> 
        </Grid> 
       </DataTemplate> 
      </ListView.ItemTemplate> 
<ListView> 

我想,在用戶控件:

<Button Content="Click" Command="{Binding Path=DataContext.OpenCommand, ElementName=peopleListBox}"/> 

這:

<Button Content="Click" Command="{Binding Path=OpenCommand, ElementName=peopleListBox}"/> 

這個代碼都不工作。

用戶控件:

<UserControl 
    x:Class="App13.UserControls.ItemTemplateControl" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local1="using:App13" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d"> 

    <Grid> 
     <Button Content="Click" Foreground="Black" Command="{Binding Path=DataContext.OpenCommand, ElementName=peopleListBox}"/> 

    </Grid> 
</UserControl> 
+0

爲什麼你要在'DataTemplate'中使用同一個命令的按鈕?該模板適用於所有項目。你是否想要一遍又一遍地使用同一個按鈕? – meilke

+1

你可以提供'UserControl'的代碼嗎? – meilke

+0

這只是一個示例,顯示如何在列表視圖中使用按鈕(不在usercontrol中) –

回答

0

不能使用peopleListBox用戶控件的XAML中。它是父控制中定義的字段,在子控件中不可訪問。

你爲我提供作品(列表視圖模板點擊按鈕調用命令處理程序)代碼:

<Window x:Class="WpfApplication1.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <ListView x:Name="peopleListBox"> 
      <ListView.ItemTemplate> 
       <DataTemplate> 
        <Grid> 
         <Button Command="{Binding 
              DataContext.OpenCommand, 
              ElementName=peopleListBox}" /> 
        </Grid> 
       </DataTemplate> 
      </ListView.ItemTemplate> 
     </ListView> 
    </Grid> 
</Window> 

我使用的視圖模型:

public class VM 
{ 
    public VM() 
    { 
     OpenCommand = new RelayCommand(o => { }); 
    } 

    public RelayCommand OpenCommand { get; set; } 
} 

這裏是主窗口構造器:

public MainWindow() 
{ 
    InitializeComponent(); 
    DataContext = new VM(); 
    peopleListBox.Items.Add(new object()); 
} 

而且顯然你不能在用戶控件裏面使用peopleListBox。它是父控制中定義的字段,在子控件中不可訪問。

+0

當我將按鈕放入ListView時,我的代碼正常工作。我不能在我的'UserControl'中使用按鈕 –

+0

檢查我的答案的底部。 – meilke

+0

將其移至頂部。 – meilke