問題描述
如何將文本框的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 user848609、max、Isak Savo、guangboo)