【问题标题】:Get data binded properties in code behind在后面的代码中获取数据绑定属性
【发布时间】:2014-08-24 01:29:26
【问题描述】:

在我的 XAML 中,我有这个属性,它就像一个魅力:

DataContext="{Binding Chat, Source={StaticResource Locator}}"

绑定正确,显示设计时数据等

但是现在我需要从 textBox 获取数据:

     <TextBox Text="{Binding MessageInput, Mode=TwoWay}"/>

我不知道如何从后面的代码中访问这个文本框(或绑定的 MessageInput 字符串)。

【问题讨论】:

  • 为您的文本框设置一个名称并访问它的 Text 属性
  • @Sajeetharan - 哦,谢谢,这很容易 :)

标签: c# wpf xaml windows-phone-8 code-behind


【解决方案1】:

丑陋的方式:

string res = (DataContext as [TypeOfYourViewModel]).MessageInput;

更好的方法:

<TextBox Name="tbMessageInput" ...>

string res = tbMessageInput.Text

【讨论】:

    【解决方案2】:

    如果您需要访问文本属性,那么您可以创建对视图模型的引用并从那里获取文本。您可以在我的代码中将 chatViewModel 替换为您的视图模型

    private string GetText()
    {
        ChatViewModel vm = this.DataContext as ChatViewModel;
    
        if(vm != null)
            return vm.MessageInput;
         else
            return string.Empty;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-02-25
      • 1970-01-01
      • 1970-01-01
      • 2011-02-15
      • 1970-01-01
      • 2013-09-17
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多