【发布时间】:2018-04-24 00:24:39
【问题描述】:
我的绑定有问题,我不知道为什么。我正在使用Devexpress MVVM。我有一个用户控件,用于根据 ObservableCollection 填充文本框,效果很好。
我的用户控件中有这个 xaml 代码。
<ItemsControl IsTabStop="False" ItemsSource="{Binding ListControls}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="{Binding RGN_INdex}" />
<TextBox Text="{Binding RGN}" Grid.Column="1" >
<TextBox.InputBindings>
<KeyBinding Key="F1" Command="{Binding InsertControlCommand}" CommandParameter="{Binding Path=RGN_INdex }" />
</TextBox.InputBindings>
</TextBox>
<Label Grid.Column="2" Content="RSN:" />
<TextBox Text="{Binding RSN}" Grid.Column="3" />
<Label Grid.Column="4" Content="SGN:" />
<TextBox Text="{Binding SGN}" Grid.Column="5" />
<Label Grid.Column="6" Content="SN:" />
<TextBox Text="{Binding SN}" Grid.Column="7" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
在我添加 InsertControlCommand 之前,上述代码一直有效。
<TextBox.InputBindings>
<KeyBinding Key="F1" Command="{Binding InsertControlCommand}" CommandParameter="{Binding Path=RGN_INdex }" />
</TextBox.InputBindings>
它给了我:
System.Windows.Data Error: 40 : BindingExpression path error: 'InsertControlCommand' property not found on 'object' ''RelativesM' (HashCode=41849684)'. BindingExpression:Path=InsertControlCommand; DataItem='RelativesM' (HashCode=41849684); target element is 'KeyBinding' (HashCode=2666760); target property is 'Command' (type 'ICommand')
当该命令和ListControls ObservableCollection 在同一个类(ViewModel)中时,为什么找不到InsertControlCommand?
这是我的ViewModelBaseInsertControlCommand 和ListControls 所在的位置。
public abstract class ViewModelBase : INotifyPropertyChanged {
public DelegateCommand<object> InsertControlCommand { get; private set; }
public ObservableCollection<Model.RelativesM> ListControls { get; set; }
public ViewModelBase() {
InsertControlCommand = new DelegateCommand<object>(InsertControlEvent);
ListControls = new ObservableCollection<Model.RelativesM>();
}
}
然后我有这个 MainViewModel:
public class MainViewModel : ViewModelBase {
}
然后在我的 MainWindow.xaml 上,我使用以下代码设置 DataContext:
<Window.DataContext>
<vm:MainViewModel/>
</Window.DataContext>
据我了解,我的代码应该可以工作。因为ListControls 和InsertControlCommand 使用相同的ViewModel,但命令没有。是什么原因?我错过了什么?
【问题讨论】:
-
这对你有用吗???
标签: c# wpf mvvm data-binding