簡體   English   中英

使用wpf和Devexpress MVVM設置文本框文本

[英]set textbox text using wpf and Devexpress MVVM

單擊按鈕時,如何使用wpf和Devexpress免費MVVM設置Text Textbox

這是我的文本框的xaml代碼

<TextBox Width="200" Grid.Column="1" Text="{Binding SelectedText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" FontSize="14"/>

這是我的VM代碼

        public virtual string SelectedText { get; set; }
        void AutoUpdateCommandExecute()
        {
            Console.WriteLine("Code is Executing");
            SelectedText = "TextBox Text is Not Changing";
        }

代碼正在執行,但不會更改Text Textbox

但是,當我在textbox鍵入內容並使用此代碼獲取該文本框的文本時。

        void AutoUpdateCommandExecute()
        {
            Console.WriteLine("Code is Executing");
            Console.WriteLine(SelectedText);
        }

它會打印我在文本框中鍵入的文本。 那我做錯了什么? 我不能設置文字嗎?

謝謝。

您選擇的文本必須是DependencyProperty,然后它將通知綁定其值已更改...

public static readonly DependencyProperty SelectedTextProperty = DependencyProperty.Register("SelectedText", typeof(string), typeof(YourClassType));

public string SelectedText
{
  get { return (string)GetValue(SelectedTextProperty ); }
  set { SetValue(SelectedTextProperty , value); }
}

要么

您的VM需要實現INotifyPropertyChanged接口,並且在SelectedText setter中,您需要觸發屬性更改事件...

public class VM : INotifyPropertyChanged
{
  public event PropertyChangedEventHandler PropertyChanged;
  private string _selectedText;
  public string SelectedText
  {
    get { return _selectedText; }
    set
    {
      _selectedText = value;
      RaisePropertyChanged("SelectedText");
    }
  }

  private void RaisePropertyChanged(string propertyName)
  {
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM