Skip to content

Instantly share code, notes, and snippets.

@yoshikazuendo
Created November 18, 2013 07:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yoshikazuendo/7524104 to your computer and use it in GitHub Desktop.
Save yoshikazuendo/7524104 to your computer and use it in GitHub Desktop.
WPFでViewModelを直接操作せず、コードビハインドでBindingした値を変更する方法です。すごく冗長ですが、やろうと思えばできるみたい。
<Grid>
<TextBox x:Name="TextBox1" Text="{Binding Value}"/>
</Grid>
public Window1()
{
InitializeComponent();
var viewModel = new TextInfo();
this.TextBox1.DataContext = viewModel;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// TextプロパティのBinding情報を取得する。(xamlなどで、該当のプロパティにBindingが記述されている事が大前提)
var expression = this.TextBox1.GetBindingExpression(TextBox.TextProperty);
if (expression != null) {
// ターゲットのDataContextに指定されたバインディングソースを取得する。
var source = expression.DataItem;
// ターゲットに対して特定のソースが設定されている事が大前提。
if (source != null) {
// バインディングパスがあるか?
if (expression.ParentBinding.Path != null) {
// バインディングパスを取得する。
var propInfo = source.GetType().GetProperty(expression.ParentBinding.Path.Path);
if (propInfo != null) {
propInfo.SetValue(source, "endo", null);
expression.UpdateTarget();
} else {
}
}
} else {
// ターゲットに対して特定のソースが設定されていないとnullになる。
}
} else {
// xamlなどで、該当のプロパティにBindingが記述されていないとnullになる。
}
}
// ViewModelとして使用するクラス。
public class TextInfo
{
public string Value { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment