我有一个DataGrid
项目集合(规则)。如果我在 DataGrid 中手动编辑这些项目之一,似乎SelectedItem
网格上的绑定停止工作(RuleListViewModelPropertyChanged
在控制器中不再被调用)。但只有当我实际更改单元格中项目的值时,否则SelectedItem
会继续正常工作。
我已经剥离了一些不相关的代码,所以这基本上就是我所拥有的。首先,我有以下内容DataGrid
:
<DataGrid x:Name="RuleTable" Grid.Row="1" Grid.ColumnSpan="2" ItemsSource="{Binding Rules}" SelectedItem="{Binding SelectedRule, Mode=TwoWay}"
BorderThickness="0" >
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding TargetValue, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True,
ValidatesOnExceptions=True, NotifyOnValidationError=True}"
Header="{x:Static p:Resources.TargetValue}" Width="*" ElementStyle="{StaticResource TextCellElementStyle}"
EditingElementStyle="{StaticResource TextCellEditingStyle}"/>
</DataGrid.Columns>
</DataGrid>
ViewModel
看起来像这样:
public class RuleListViewModel : ViewModel<IRuleListView>
{
private IEnumerable<Rule> rules;
private Rule selectedRule;
public RuleListViewModel(IRuleListView view)
: base(view)
{
}
public RuleListViewModel() : base(null) {}
public IEnumerable<Rule> Rules
{
get
{
return rules;
}
set
{
if (rules != value)
{
rules = value;
RaisePropertyChanged("Rules");
}
}
}
public Rule SelectedRule
{
get
{
return selectedRule;
}
set
{
if (selectedRule != value)
{
selectedRule = value;
RaisePropertyChanged("SelectedRule");
}
}
}
}
最后一个Controller
看起来像这样:
public class RuleController : Controller
{
private readonly IShellService shellService;
private readonly RuleListViewModel ruleListViewModel;
private readonly DelegateCommand addRuleCommand;
private readonly DelegateCommand deleteRuleCommand;
[ImportingConstructor]
public RuleController(IShellService shellService, IEntityService entityService, RuleListViewModel ruleListViewModel)
{
this.shellService = shellService;
this.ruleListViewModel = ruleListViewModel;
}
public void Initialize()
{
AddWeakEventListener(ruleListViewModel, RuleListViewModelPropertyChanged);
shellService.RuleListView = ruleListViewModel.View;
List<Rule> rules = GetRules();
ruleListViewModel.Rules = new ObservableCollection<Rule>(rules);
}
private void RuleListViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "SelectedRule")
{
// This never gets called after edit
}
}
}
我真的不知道问题出在哪里,但是由于我实际上必须更改值才能体验这种行为(仅单击单元格而不编辑任何内容都可以正常工作)我猜这与SelectedItem
绑定中断有关我更改绑定到它的项目的值?!