当 itemSource 绑定到模型 (\

问题描述

我有一个包含 ListView 的 UserControl(视图)。 itemsSource 绑定到 Model 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,3,0"/>
    <Border Grid.Column="1" BorderBrush="white" BorderThickness="0,0"/>
    <Border Grid.Column="2" BorderBrush="white" BorderThickness="0,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 个按钮的 View 的 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 原则? 谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)