コードビハインドでUI固有の作業を行い、データコンテキストでバインディングを更新するUI要素がいくつかあります。
WPF 要素:
<TextBox Grid.Row="1"
Text="{Binding PartNumber, UpdateSourceTrigger=Explicit}"
Name="ui_partNumber"
FontSize="35"
VerticalContentAlignment="Center" />
<Button Grid.Column="1"
Grid.Row="1"
Content="OK"
Click="PartOKClick"
FontSize="20"
Width="150" />
コードビハインド:
/// <summary>
/// Handle updating the view model with the part number
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PartOKClick(object sender, RoutedEventArgs e) {
//Get the textbox's binding expression
BindingExpression be = ui_partNumber.GetBindingExpression(TextBox.TextProperty);
if (Condition) {
//Update part number binding
be.UpdateSource();
//Animate to next state
InAnimate(ui_partGrid.Name);
OutAnimate(ui_whichPartNumber.Name);
}
else {
//Discard the text in the textbox
be.UpdateTarget();
//Animate to notification state
InAnimate(ui_invalidLocation.Name);
}
}
私の ViewModel のプロパティは次のようになります。
public string PartNumber{
get { return _partNumber; }
set { _partNumber = value; OnPropertyChanged("PartNumber"); }
}
私は明示的なバインディングを使用しており、チェックアウトした場合にのみソースを更新しています。それ以外の場合は、元のバインディングに戻っています。
問題は、これがバインディングを明示的に操作するための最良の方法であるかということです。さまざまなタイプの 100 個の要素の BindingExpression を取得している場合、毎回手動で行う必要がありますか? もっと再利用可能な方法でそれを行うことができますか?