C# 加载xml/xaml并定义键绑定

C# 加载xml/xaml并定义键绑定,c#,wpf,mvvm,C#,Wpf,Mvvm,这是我的xaml的一部分: <DataGrid ItemsSource="{Binding listImages, UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False" Name="dataGrid1" Height="341" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Margin="10,10,10,0" Width="225" Can

这是我的xaml的一部分:

<DataGrid ItemsSource="{Binding listImages, UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False" Name="dataGrid1" Height="341" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Margin="10,10,10,0" Width="225" CanUserResizeRows="False" CanUserResizeColumns="False" CanUserReorderColumns="False" CanUserAddRows="False" IsHitTestVisible="True" OverridesDefaultStyle="False" SelectedIndex="0" SelectionUnit="FullRow" SelectionMode="Single">
<DataGrid.InputBindings>

    <KeyBinding Key="a" Command="{Binding Path=KeyPressed}"/>                    
    <KeyBinding Key="s" Command="{Binding Path=KeyPressed}"/>
    <KeyBinding Key="d" Command="{Binding Path=KeyPressed}"/> 

</DataGrid.InputBindings>
<DataGrid.RowStyle>
    <Style TargetType="DataGridRow">
        <Setter Property="Background" Value="{Binding rowColor}"/>
    </Style>
</DataGrid.RowStyle>
<DataGrid.Columns>                   
    <DataGridTextColumn Header="ImageName" Binding="{Binding imageName}" Width="112" />
    <DataGridTextColumn Header="Tag" Binding="{Binding tag}" Width="110" />
</DataGrid.Columns>

我想加载一个.xaml,其中只定义了这个datagrid,或者更好地定义了键绑定。这是因为用户可以更改可以绑定的密钥

汤姆想用z、x、c键代替a、s、d键。为此,他编辑默认的xml/xaml(位于某处),并更改KeyBinding的Key参数并加载它

新的xml/xaml将如下所示:

<DataGrid ItemsSource="{Binding listImages, UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False" Name="dataGrid1" Height="341" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Margin="10,10,10,0" Width="225" CanUserResizeRows="False" CanUserResizeColumns="False" CanUserReorderColumns="False" CanUserAddRows="False" IsHitTestVisible="True" OverridesDefaultStyle="False" SelectedIndex="0" SelectionUnit="FullRow" SelectionMode="Single">
<DataGrid.InputBindings>

    <KeyBinding Key="z" Command="{Binding Path=KeyPressed}"/>                    
    <KeyBinding Key="x" Command="{Binding Path=KeyPressed}"/>
    <KeyBinding Key="c" Command="{Binding Path=KeyPressed}"/> 

</DataGrid.InputBindings>
<DataGrid.RowStyle>
    <Style TargetType="DataGridRow">
        <Setter Property="Background" Value="{Binding rowColor}"/>
    </Style>
</DataGrid.RowStyle>
<DataGrid.Columns>                   
    <DataGridTextColumn Header="ImageName" Binding="{Binding imageName}" Width="112" />
    <DataGridTextColumn Header="Tag" Binding="{Binding tag}" Width="110" />
</DataGrid.Columns>


是否可以按照MVVM模式执行此操作?

我不会将用户的键绑定选择持久化为XAML<代码>绑定标记等对用户来说毫无意义

相反,以其他更友好的方式保留键绑定,甚至可能是一个简单的ini样式文本文件,例如:

Command1Key=z
Command2Key=x
Command3Key=c
一旦将它们加载到ViewModel中,就可以将它们作为
InputBindingCollection
属性公开到视图中,然后视图可以根据该属性进行绑定