ContentControl绑定和DataTemplates即使生效也会产生绑定错误

时间:2013-10-21 16:49:10

标签: c# wpf mvvm datatemplate contentcontrol

我正在尝试使用ContentControl和DataTemplate在我的代码中切换视图模型。代码工作,它似乎正确绑定,但我在输出中得到一个错误:

System.Windows.Data Error: 40 : BindingExpression path error: 'Value1' property not found on 'object' ''ViewModel2' (HashCode=1202201)'. BindingExpression:Path=Value1; DataItem='ViewModel2' (HashCode=1202201); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')
System.Windows.Data Error: 40 : BindingExpression path error: 'Value2' property not found on 'object' ''ViewModel1' (HashCode=7634749)'. BindingExpression:Path=Value2; DataItem='ViewModel1' (HashCode=7634749); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')

MainView(容器)的代码:

<DataTemplate DataType="{x:Type local:ViewModel1}" >
    <local:View1 DataContext="{Binding ElementName=UserControlContainer, Path=Content}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:ViewModel2}" >
    <local:View2 DataContext="{Binding ElementName=UserControlContainer, Path=Content}"/>
</DataTemplate>
...
<ContentControl x:Name="UserControlContainer" Content="{Binding CurrentViewModel}"/>

MainViewModel.cs包含:

    private ViewModelBase m_viewModel = null;
    public ViewModelBase CurrentViewModel
    {
        get
        {
            return m_viewModel;
        }
        set
        {
            m_viewModel = value;
            RaisePropertyChanged("CurrentViewModel");
        }
    }
    private void EventTimer(object sender, EventArgs e)
    {
        if (CurrentViewModel == null || CurrentViewModel.GetType() == typeof(ViewModel1))
        {
            CurrentViewModel = new ViewModel2();
        }
        else
        {
            CurrentViewModel = new ViewModel1();
        }
        CommandManager.InvalidateRequerySuggested();
    }

ViewModel1和ViewModel2都有相同的代码,只是它们引用自己的viewmodel及其上的属性(ViewModel1为Value1,ViewModel2为Value2):

ViewModel1:

public class ViewModel1 : ViewModelBase
{
    public double m_value = new Random((int)DateTime.Now.ToBinary()).NextDouble();

    public string Value1
    {
        get { return m_value.ToString(); }
    }
}

视图1:

<TextBlock Text="{Binding Value1}"/>

我想问题是,当计时器更改属性CurrentViewModel中的ViewModel时,未显示的视图仍在内存中并尝试绑定到错误的ViewModel(因此View2尝试从ViewModel1获取Value2)。 / p>

有什么方法可以解决这个问题吗?因此,只有当CurrentViewModel的类型属于正确类型时才会发生绑定。 (我可以使用转换器并将期望的类型作为参数传递但是,有没有更好的解决方案?)

谢谢!

0 个答案:

没有答案
相关问题