我想访问绑定到视图模型中文本框的依赖项属性。 在视图模型中,我有以下代码:
Answer _Answer = new Answer();
_Answer.GetValue(Answer.Deutsch1AnswerProperty);
Console.WriteLine(_Answer.Deutsch1Answer);
依赖属性定义如下:
public class Answer : DependencyObject
{
// Ereignis
public event EventHandler Deutsch1AnswerChanged;
public static readonly DependencyProperty Deutsch1AnswerProperty;
public String Deutsch1Answer
{
get { return (String)GetValue(Deutsch1AnswerProperty); }
set { SetValue(Deutsch1AnswerProperty, value); }
}
public static void OnDeutsch1AnswerChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
Answer _Answer = (Answer)sender;
if (_Answer.Deutsch1AnswerChanged != null)
_Answer.Deutsch1AnswerChanged(_Answer, null);
}
static Answer()
{
FrameworkPropertyMetadata meta = new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault);
meta.PropertyChangedCallback = new PropertyChangedCallback(OnDeutsch1AnswerChanged);
Deutsch1AnswerProperty = DependencyProperty.Register("Deutsch1Answer", typeof(String), typeof(Answer), meta);
}
}
在MainWindow.Xaml中我有以下代码:
<Window.Resources>
<local:Answer x:Key="_Answer" Deutsch1Answer=string.Empty />
</Window.Resources>
<Grid Definitions ...>
<TextBox Grid.Column="1" Grid.Row="2" Name="BoxDeutsch1" Text="{Binding Source={StaticResource _Answer}, Path=Deutsch1Answer}">
</TextBox>
我无法访问视图模型中的Text属性。请帮忙。
视图模型如下所示:
public class VokabelViewModel : INotifyPropertyChanged
{
private Vokabel _Model;
public VokabelViewModel(Vokabel model)
{
_Model = model;
}
private ICommand _boxDeutsch1_HitEnter;
public ICommand BoxDeutsch1_HitEnter
{
get
{
return _boxDeutsch1_HitEnter ?? (_boxDeutsch1_HitEnter = new CommandHandler(() => MyActionBoxDeutsch1_HitEnter(), _canExecuteBoxDeutsch1_HitEnter));
}
}
private bool _canExecuteBoxDeutsch1_HitEnter;
public void MyActionBoxDeutsch1_HitEnter()
{
Answer _Answer = new Answer();
_Answer.GetValue(Answer.Deutsch1AnswerProperty);
_Model.TestVokabel(_Answer.Deutsch1Answer);
}
答案 0 :(得分:1)
如果要访问ViewModel中的Deutsch1Answer DependencyProperty,则应绑定它。 但是,我真的没有看到你为什么得到&#34;答案&#34; -class。
如果要将文本框文本绑定到视图模型中的属性,则应添加Answer属性并将其直接绑定到文本框。
在ViewModel中:
private string m_answer;
public string Answer
{
get { return m_answer; }
set
{
m_answer = value;
OnPropertyChanged("Answer");
}
}
在您的视图中:
...
<TextBox Grid.Column="1" Grid.Row="2" Name="BoxDeutsch1" Text="{Binding Answer}">
...