c# - MVVM WPF 中的 ICommand

标签 c# wpf mvvm

我正在看这个 MVVM 的东西,我遇到了一个问题。

情况很简单。

我的 index.xaml 页面中有以下代码

    <Grid>
    <ItemsControl ItemsSource="{Binding}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <view:MovieView ></view:MovieView>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

在我的 index.xaml.cs 中

...

初始化组件(); base.DataContext = new MovieViewModel(ent.Movies.ToList()); ....

这是我的 MoveViewModel

    public class MovieViewModel
{
    readonly List<Movies> _m;
    public ICommand TestCommand { get; set; }
    public MovieViewModel(List<Movies> m)
    {
        this.TestCommand = new TestCommand(this);
        _m = m;
    }
    public List<Movies> lm
    {
        get
        {
            return _m;
        }
    }
}

最后

这是我的控件 xaml MovieView

    <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"></ColumnDefinition>
        <ColumnDefinition Width="Auto"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Label VerticalAlignment="Center" Grid.Row="0" Grid.Column="0">Title :</Label><TextBlock VerticalAlignment="Center" Grid.Row="0" Grid.Column="1" Text="{Binding Title}"></TextBlock>  
    <Label VerticalAlignment="Center" Grid.Row="1" Grid.Column="0">Director :</Label><TextBlock VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" Text="{Binding Director}"></TextBlock>
    <Button Grid.Row="2" Height="20" Command="{Binding Path=TestCommand}" Content="Edit" Margin="0,4,5,4" VerticalAlignment="Stretch" FontSize="10"/>
</Grid>

所以我遇到的问题是,如果我将 ItemsSource 设置为 Binding

什么都没做

如果我设置 ItemsSource="{Binding lm}"

它填充了我的 itemsControl 但命令 (Command="{Binding Path=TestCommand}") 不起作用。

当然不行,因为TestCommand不属于我的实体对象Movies。

最后我的问题是,

我需要将什么传递给 ItemsControl 才能使其正常工作?

提前致谢

最佳答案

一旦您的项目被呈现,每个项目都会设置为它所代表的特定行的 DataContext,因此您不再能够引用您的第一个 DataContext。此外,由于您处于DataTemplate,当需要该模板时,您的绑定(bind)将开始工作。所以在这种情况下,您需要通过 RelativeSource 绑定(bind)查找您的父控件...

希望这能解释一些事情..

关于c# - MVVM WPF 中的 ICommand,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/642043/

相关文章:

C#解析 "(true and true) or (true or false)"

c# - 跨类库传递 System.Drawing.Bitmap 不可靠吗?

c# - 将资源转换为 byte[]

wpf - 使用 MVVM 还是不使用 MVVM,这是一个问题

c# - WPF圆形边框按钮,响应单击颜色变化

c# - 在运行程序中执行方法而不是启动新实例

c# - Mongodb - 实体序列化正常,但反序列化时出现 'No serializer found for type' 错误

c# - RelayCommand 不会在按钮单击时执行

c# - Mahapp ShowMessageAsync MvvM

c# - 调用主体中包含 JObject 的 Web Api