c# - 单击 DataGrid 元素打开新 View (WPF xaml 应用程序)

标签 c# wpf xaml mvvm datagrid

我有使用 MVVM 架构编写的 WPF 应用程序,所以我有模型、 View 和 View 模型。我的 View 中有一个 DataGrid,其中包含 Product 的列表(其中包含多个字段:名称、余额等)。

我想添加额外的窗口/ View ,点击 DataGrid 中的元素后会出现。是否可以?如果是,怎么办?

我对 xaml 代码很感兴趣,而不是像 button1_Click 这样的东西。

这就是我现在所拥有的:

<Window ...
    Height="600" Width="800"
    WindowState="Maximized">
<Grid>
    <DataGrid AutoGenerateColumns="False"
              CanUserAddRows="False"
              CanUserResizeRows="False"
              IsReadOnly="True"
              SelectionMode="Single"
              SelectionUnit="FullRow"
              ItemsSource="{Binding Path=Products}"
              SelectedItem="{Binding Path=CurrentProduct, Mode=TwoWay}"
              >
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Path=ProductName}"
                                Header="Product Name"
                                Width="*" />
            <DataGridTextColumn Binding="{Binding Path=Balance}"
                                Header="Balance"
                                Width="Auto" />
            ...
        </DataGrid.Columns>
    </DataGrid>
</Grid>

最佳答案

当您右键单击数据网格的某个元素时,这将触发一个命令:

<DataGrid.InputBindings>
    <MouseBinding
        MouseAction="RightClick"
        Command="{Binding yourCommand,Mode=OneWay}"
    />
</DataGrid.InputBindings>

运行新 View :

var win = new Window();
win.Content = new yourNewViewModel();
win.SizeToContent = SizeToContent.WidthAndHeight; //Adjust window size to content
win.Show();

您必须在 App.xaml 中将 yourNewViewModel 与 yourNewView 链接起来:

<DataTemplate DataType="{x:Type yourProjectViewModel:yourNewViewModel}">
    <local:yourNewView/>
</DataTemplate>

不要忘记将您的 ProjectViewModel 的 xmlns 添加到您的 App.xaml

关于c# - 单击 DataGrid 元素打开新 View (WPF xaml 应用程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33009072/

相关文章:

c# - FirstOrDefault/First 和 OrderByDescending 是否比 LastOrDefault/Last 和 OrderBy 更快?

c# - 更改样式控件中的部分控件模板?

c# - C# 中的多语言支持

c# - 在 Twitch 中使用 IRC-Client 时 WPF-App 无法使用 [C#]

c# - 亲子关系界面

wpf - XAML 中从形状到路径的转换

wpf - WPF 如何处理对空对象属性的绑定(bind)?

c# - 使用复杂数据类型在 EF 中调用存储过程

wpf - 用于转换为 MVVM 模式的事件名称

wpf - 修改组合框的ItemsSource ObservableCollection后如何刷新组合框