【发布时间】:2021-08-15 01:39:29
【问题描述】:
我有一个具有 ListView 的 UserControl(视图)。 itemsSource 绑定到模型 Character.cs。我将 ListView.ItemTemplate 设置为另一个视图,在该视图中是 3 个字符串的位置和用于选择字符的按钮。这三个字符串需要用模型中的数据填充(这已完成),但按钮的命令需要绑定到 ViewModel 中的 ICommand。我无法访问此命令,因为 itemsSource 绑定到一个字符,它将带有按钮的视图的 dataContext 设置为一个字符。
这是具有 ListView 的 UserControl(视图)
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!--disable the selected item thingyyy??-->
<ListView ItemsSource="{Binding Characters}"
SelectedItem="{Binding CharacterItemVM.BoundCharacter}"
Background="{StaticResource BackGroundColorDark}"
HorizontalContentAlignment="Stretch">
<ListView.ItemTemplate>
<DataTemplate>
<v:CharacterItemView Grid.Column="0"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
这是具有 3 个字符串和一个按钮的视图
<Grid Background="{StadticResource BackGroundColor}">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Border Grid.Column="0" BorderBrush="white" BorderThickness="0,0,3,0"/>
<Border Grid.Column="1" BorderBrush="white" BorderThickness="0,0,3,0"/>
<Border Grid.Column="2" BorderBrush="white" BorderThickness="0,0,3,0"/>
<Label FontSize="18" Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center"
Content="{Binding Name, FallbackValue=N/A}"/>
<Label FontSize="18" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center"
Content="{Binding CharacterClass, FallbackValue=N/A}"/>
<Label FontSize="18" Grid.Column="2" HorizontalAlignment="Center" VerticalAlignment="Center"
Content="{Binding Level, FallbackValue=N/A}"/>
<Button Content="select" FontSize="18" Grid.Column="3" Background="DarkGray"
Foreground="white" BorderThickness="3" BorderBrush="LightCyan"
Margin="15" Command="{Binding SelectCharacterCommand}"/>
</Grid>
这是带有 3 个按钮的视图的 ViewModel
public class CharacterItemViewModel : ObservableObject
{
private Character boundCharacter;
public Character BoundCharacter
{
get { return boundCharacter; }
set { OnPropertyChaged(ref boundCharacter, value); }
}
ICommand SelectCharacterCommand;
//TODO: get the characterStore from BookVM
public CharacterItemViewModel(CharacterStore characterStore)
{
SelectCharacterCommand = new SelectCharacterCommand(characterStore, this,
boundCharacter);
}
}
我希望按钮使用 CharacterItemViewModel 类中的 SelectCharacterCommand。你会如何建议我更改代码来实现这一点,同时仍然坚持 MVVM 原则? 谢谢!
【问题讨论】:
标签: c# wpf listview datatemplate itemssource