如何將文本框的borderBrush屬性綁定到viewmodel中的屬性,類型轉換錯誤 (How to bind the borderBrush property of a textbox to a property in viewmodel, type conversion error)


問題描述

如何將文本框的borderBrush屬性綁定到viewmodel中的屬性,類型轉換錯誤 (How to bind the borderBrush property of a textbox to a property in viewmodel, type conversion error)

I have a textbox in xaml with a borderbrush property as follows:

<textbox BorderBrush="{Binding MyBrush}" />

inside view model I have defind the property

public System.Windows.Media.Brushes MyBrush {get;set;}

but I cannot set a value to this property

void method()
{
 MyBrush = System.Windows.Media.Brushes.Red;
}

the compiler error is : cannot implicitly convert type System.Windows.Media.SolidColorBrush to System.Windows.Media.Brushes


參考解法

方法 1:

change

public System.Windows.Media.Brushes MyBrush {get;set;}

to

public System.Windows.Media.Brush MyBrush {get;set;}

方法 2:

Brushes is a static class containing pre-defined brush instances.

The type of your property should be Brush

方法 3:

You should use INotifyPropertyChanged. The code like :

private System.Windows.Media.Brush _myBrush
public System.Windows.Media.Brush MyBrush {
    get { return _myBrush; }
    set {
        if(value != _myBrush) {
            _myBrush = value;
            OnPropertyChanged("MyBrush");
        }
    }
}

protected virtual void OnPropertyChanged(string propertyName) {
    // ....
}

(by user848609maxIsak Savoguangboo)

參考文件

  1. How to bind the borderBrush property of a textbox to a property in viewmodel, type conversion error (CC BY-SA 3.0/4.0)

#mvvm #wpf #wpf-controls #C#






相關問題

WPF View 在關閉時將 ViewModel 屬性設置為 null (WPF View sets ViewModel properties to null on closing)

在文本框中正確輸入後啟用按鈕 (Button Enable After Correct Input In TextBox)

WPF說數據項不為空時為空 (WPF says that data item is null when it is not null)

MVVM - 如何將 ViewModel 包裝在 ViewModel 中? (MVVM - How to wrap ViewModel in a ViewModel?)

關於服務參考和 MVVM 模式的幾個一般問題 (A few general questions about Service Reference and MVVM pattern)

WPF MVVM 鏈接視圖 (WPF MVVM Linked Views)

wpf 樹視圖 mvvm (wpf treeview mvvm)

如何在 MVVM Light 的 ListView 中的 ComboBox 中顯示列表? (How to show a List in a ComboBox in a ListView in MVVM Light?)

多次調用 PropertyChanged 的 ViewModel 屬性 (ViewModel properties with multiple calls to PropertyChanged)

如何將圖像存儲在類庫中並從任何類訪問它 (How can i store an image in a class library and access it from any class)

Silverlight MVVM 隔離存儲 (Silverlight MVVM Isolated Storage)

如何將文本框的borderBrush屬性綁定到viewmodel中的屬性,類型轉換錯誤 (How to bind the borderBrush property of a textbox to a property in viewmodel, type conversion error)







留言討論