我有一個用戶控件的UserControl
有一個DependencyProperty
這臺在代碼隱藏(我想這可能是我的問題的根源,但還是不知道該怎麼做):綁定從DependencyProperty的工作不
用戶控件
public partial class MyControl
{
public MyControl()
{
InitializeComponent();
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(MyControl),
new FrameworkPropertyMetadata("",FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); InvokePropertyChanged(new PropertyChangedEventArgs("Text"));}
}
public static string GetText(DependencyObject obj)
{
return (string)obj.GetValue(TextProperty);
}
public static void SetText(DependencyObject obj, string value)
{
obj.SetValue(TextProperty, value);
}
private void ChangeText()
{
Text="some value";
}
}
在我View.xaml我用這個控制這樣的:
<MyControl Text="{Binding Text, RelativeSource={RelativeSource Self}, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
而在我的ViewModel的Text屬性:
private string _text;
public string Text
{
get { return _text; }
set { _text= value; InvokePropertyChanged(new PropertyChangedEventArgs("Text"));}
}
的問題:在視圖模型 Text屬性永遠不會被更新;當使用像TextBox這樣的常規控件進行綁定時,所有工作都是完美的;如果我在XAML中設置文本,UserControl更新的文本。 我做錯了什麼?
UPDATE 我的問題是,我已經在MyControl設置的DataContext明確。
這不工作太...... :(當我通過調用ChangeText()更改MyControl中的屬性時,它不會更改ViewModel的Text屬性 – lena
非常感謝您的筆記,儘管 – lena
您確定已將DataContext設置爲指向ViewModel在你的包含控制MyControl(可能是窗口,另一個用戶控件等)。還有沒有你明確地設置DataContext MyControl?你能在輸出窗口中尋找任何綁定錯誤嗎?ViewModel中的Text屬性getter被擊中上負載? –