小编str*_*000的帖子

WPF绑定OneWayToSource在更改DataContext时将源属性设置为“”

我设置了目标控件的DataContext时,OneWayToSource绑定的行为异常。源的属性被设置为默认值,而不是目标控件的属性值。

我在标准WPF窗口中创建了一个非常简单的程序来说明我的问题:

XAML

<StackPanel>
  <TextBox x:Name="tb"
    Text="{Binding Path=Text,Mode=OneWayToSource,UpdateSourceTrigger=PropertyChanged}"
    TextChanged="TextBox_TextChanged"/>

  <Button Content="Set DataContext" Click="Button1_Click"/>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

MainWindow.cs

public partial class MainWindow : Window
{
   private ViewModel _vm = new ViewModel();

   private void Button1_Click(object sender, RoutedEventArgs e)
   {
      Debug.Print("'Set DataContext' button clicked");
      tb.DataContext = _vm;
   }

   private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
   {
      Debug.Print("TextBox changed to " + tb.Text);
   }
}
Run Code Online (Sandbox Code Playgroud)

ViewModel.cs

public class ViewModel
{
   private string _Text;
   public string Text
   {
      get { return _Text; }
      set
      {
         Debug.Print(
            "ViewModel.Text (old …
Run Code Online (Sandbox Code Playgroud)

c# wpf xaml binding

5
推荐指数
1
解决办法
2067
查看次数

标签 统计

binding ×1

c# ×1

wpf ×1

xaml ×1