我有一个问题。我想向按钮提供来自 ViewModel 的命令,该命令位于 ItemsRepeater ItemsSource 之外。我需要有关如何进行此类绑定的帮助
我的 ItemsRepeater 中的按钮
<Button Command={Binding TestClick} Grid.Column="0" HorizontalAlignment="Stretch" Foreground="#6264a7" HorizontalContentAlignment="Center" CornerRadius="0" Background="#2f2f2f" FontSize="20">Details</Button>
我的物品中继器
<ItemsRepeater.ItemTemplate>
<DataTemplate>
<DockPanel Margin="30,0,30,50">
<StackPanel>
<TextBlock Background="#2f2f2f" FontSize="25" Foreground="AntiqueWhite" TextAlignment="Center" Padding="0,8,0,8" Text="{Binding Name}"></TextBlock>
<TextBlock TextAlignment="Center" Background="#2f2f2f" Foreground="AntiqueWhite" Height="40" FontSize="20" Padding="0,8,0,0" Text="{Binding Date}"></TextBlock>
<TextBlock TextAlignment="Center" Background="#2f2f2f" Foreground="AntiqueWhite" Height="40" FontSize="20" Padding="0,2,0,0" Text="{Binding EventType}"></TextBlock>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50*" />
<ColumnDefinition Width="50*" />
</Grid.ColumnDefinitions>
<Button Command={Binding TestClick} Grid.Column="0" HorizontalAlignment="Stretch" Foreground="#6264a7" HorizontalContentAlignment="Center" CornerRadius="0" Background="#2f2f2f" FontSize="20">Details</Button>
<Button Grid.Column="1" HorizontalAlignment="Stretch" HorizontalContentAlignment="Center" Foreground="#a4373a" CornerRadius="0" Background="#2f2f2f" FontSize="20">Delete</Button>
</Grid>
<ProgressBar Height="10" CornerRadius="0" Value="{Binding TimeLeft}" Minimum="0" Maximum="{Binding DifferenceBetweenDates}" Foreground="{Binding ProgressBarColour}" />
</StackPanel>
</DockPanel>
</DataTemplate>
</ItemsRepeater.ItemTemplate>
</ItemsRepeater>
我的视图模型:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Anniverse.ViewModels
{
class MainPanelViewModel : ViewModelBase
{
public string CurrentDate => DateTime.Today.ToString("dd.MM.yyyy");
public ObservableCollection<Event> Events => new Connector().GetEvents();
public void TestClick()
{
Console.WriteLine("Hello test");
}
}
}
实现这一点的最简单方法是绑定到祖先
Command="{Binding $parent[ItemsRepeater].DataContext.YourCommand}"
请注意,您需要在视图模型中定义
ICommand
才能使命令绑定正常工作,您可以在 here 找到示例
编辑: 我没有意识到这一点,但直接绑定到方法应该也可以工作
我可能会迟到,但对于那些尝试@radoslawik 的答案但遇到此类错误的人
Unable to resolve property or method of name 'YourCommand' on type 'System.Object'
这是由于编译后的绑定无法知道数据上下文的真实类型造成的。 但是,有一个解决方法:通过强制转换:
Command="{Binding $parent[ItemsControl].((vm:YouViewModel)DataContext).YourCommand}"