C#:WPF MVVM中的按钮绑定
因此,我有一个带有ItemsControl的视图,它绑定到某个ObservableCollection。在DataTemplate中,我需要两个按钮。当我尝试将这些按钮绑定到我定义它们的位置,并启动应用程序时,在单击按钮时不会发生任何事情 观点:C#:WPF MVVM中的按钮绑定,c#,wpf,mvvm,C#,Wpf,Mvvm,因此,我有一个带有ItemsControl的视图,它绑定到某个ObservableCollection。在DataTemplate中,我需要两个按钮。当我尝试将这些按钮绑定到我定义它们的位置,并启动应用程序时,在单击按钮时不会发生任何事情 观点: <UserControl x:Class="GraphicalUserInterface.Views._2_ToDoList.ToDoListMainView" xmlns="http://schemas.microsoft.c
<UserControl x:Class="GraphicalUserInterface.Views._2_ToDoList.ToDoListMainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:GraphicalUserInterface.Views._2_ToDoList"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="600"
DataContext="{Binding Source={StaticResource Locator}, Path=ToDoListMain}">
<Grid>
<ItemsControl Margin="5" ItemsSource="{Binding ListEntries}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border CornerRadius="5" BorderThickness="2" BorderBrush="Black" Height="50" Margin="5">
<StackPanel Orientation="Horizontal" Margin="0,5">
<Label FontWeight="Bold">Customer:</Label>
<Label Content="{Binding Customer}" Margin="0,0,20,0"/>
<Label FontWeight="Bold">Trainer:</Label>
<Label Content="{Binding Trainer}" Margin="0,0,20,0"/>
<Label FontWeight="Bold">Date:</Label>
<Label Content="{Binding Date}" Margin="0,0,20,0"/>
<Label FontWeight="Bold">RequestType:</Label>
<Label Content="{Binding RequestType}" Margin="0,0,20,0"/>
<Button Margin="5" Width="100" CommandParameter="{Binding}" Command="{Binding Path=DataContext.ContactBtnClickCommand, RelativeSource= {RelativeSource FindAncestor,AncestorType={x:Type ItemsControl}}}">Contact</Button>
<Button Margin="5" Width="100" CommandParameter="{Binding}" Command="{Binding DataContext.AcceptBtnClickCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}">Accept</Button>
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
命令属性必须是带有getter的属性。不能绑定到字段
public RelayCommand<ToDoVM> AcceptBtnClickCommand { get; private set; }
public RelayCommand<ToDoVM> ContactBtnClickCommand { get; private set; }
命令属性必须是带有getter的属性。不能绑定到字段
public RelayCommand<ToDoVM> AcceptBtnClickCommand { get; private set; }
public RelayCommand<ToDoVM> ContactBtnClickCommand { get; private set; }
尝试将AncestorType更改为
UserControl
。ItemsControl数据上下文是ListEntries,不包含命令。您需要向上引用包含命令的上下文。@EdPlunkett,我刚刚仔细看了一下,打算删除注释尝试将AncestorType更改为UserControl
。ItemsControl数据上下文是ListEntries,不包含命令。您需要向上引用包含命令的上下文。@EdPlunkett,我只是仔细看了一下,准备删除注释
public RelayCommand<ToDoVM> AcceptBtnClickCommand { get; private set; }
public RelayCommand<ToDoVM> ContactBtnClickCommand { get; private set; }
Command="{Binding DataContext.ContactBtnClickCommand, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"