我想在TabControl
步骤中将StepViewModel
的内容绑定到ObservableCollection
的实例。
我的ProcessViewModel:
pubic class ProcessViewModel : ViewModelBase
{
public ObservableCollection<StepViewModel> Steps
{
get { return _steps; }
set { _steps = value; OnPropertyChanged("Steps"); }
}
public StepViewModel SelectedStep
{
// like above...
}
}
我的StepViewModel(DataContext应该是ProcessVM步骤中的StepVM):
public class StepViewModel : ViewModelBase
{
public string Name { get {...} set {...} }
public object Media { get {...} set {...} }
//...
}
我的TabControl(DataContext是ProcessViewModel):
<C1:C1TabControl
ItemsSource="{Binding Steps}"
SelectedItem="{Binding SelectedStep}"
SelectionChanged="{tcSteps_OnSelectionChanged">
<C1:C1TabControl.ContentTemplate>
<DataTemplate>
<local:StepView
DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type vmns:ProcessViewModel}}, Path=SelectedStep}"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
</local:StepView>
</DataTemplate>
</C1:C1TabControl.ContentTemplate>
</C1:C1TabControl>
编译器提供以下输出消息:
“System.Windows.Data错误:40:BindingExpression路径错误: 在'object'''StepViewModel'上找不到'SelectedStep'属性 (的HashCode = 32952144)”。 BindingExpression:路径= SelectedStep; DataItem ='StepViewModel'(HashCode = 32952144);目标元素是 'StepView'(Name ='StepView'); target属性是'DataContext'(类型 '对象')“
有谁知道我怎么解决? 谢谢!
答案 0 :(得分:1)
看起来在StepView的DataContext绑定上,RelativeSource可能存在一些小问题。由于模板不是可视化树的一部分,因此我认为您不能使用FindAncestor。您可以使用StaticResource作为指向主DataContext的指针(例如http://www.codeproject.com/Articles/27432/Artificial-Inheritance-Contexts-in-WPF),但我认为在这种情况下仅使用ElementName进行搜索可能更简单。该方法看起来像这样:
更新您的TabControl以获取名称,因此可以通过ElementName搜索绑定
<C1:C1TabControl
x:Name="MyTabControl"
ItemsSource="{Binding Steps}"
SelectedItem="{Binding SelectedStep}"
SelectionChanged="{tcSteps_OnSelectionChanged">
更新StepView以按ElementName查找TabControl的DataContext
<local:StepView DataContext="{Binding ElementName=MyTabControl, Path=DataContext.SelectedStep}"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
</local:StepView>