Created
November 18, 2013 07:44
-
-
Save yoshikazuendo/7524104 to your computer and use it in GitHub Desktop.
WPFでViewModelを直接操作せず、コードビハインドでBindingした値を変更する方法です。すごく冗長ですが、やろうと思えばできるみたい。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Grid> | |
<TextBox x:Name="TextBox1" Text="{Binding Value}"/> | |
</Grid> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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になる。 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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