我有個問題。我想從 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");
}
}
}
uj5u.com熱心網友回復:
實作這一目標的最簡單方法是系結到祖先
Command="{Binding $parent[ItemsRepeater].DataContext.YourCommand}"
請注意,您需要ICommand在視圖模型中為命令系結定義 以使其作業,您可以在此處找到示例
編輯:我不知道,但直接系結到方法也應該有效
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/386139.html
