我有一个带Window
的MVVM应用程序,它应该根据子视图模型显示内容。我使用ContentControl
和数据模板,这很好用:
<Window x:Class="ContentControlApplication.DialogWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ContentControlApplication"
Height="350" Width="525">
<Window.Resources>
<DataTemplate DataType="{x:Type local:TestViewModel}" >
<local:TestControl DataContext="{Binding}"/>
</DataTemplate>
</Window.Resources>
<ContentControl Content="{Binding SubViewModel}" x:Name="myPresenter" />
</Window>
public partial class DialogWindow : Window
{
public DialogWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
}
}
public class MainViewModel
{
public object SubViewModel
{
get;
set;
}
public MainViewModel()
{
SubViewModel = new TestViewModel();
}
}
public class TestViewModel
{
public string TestProperty
{
get;
set;
}
public TestViewModel()
{
TestProperty = "_TEST_";
}
}
<UserControl x:Class="ContentControlApplication.TestControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ContentControlApplication">
<Grid>
<TextBlock Text="{Binding Path=TestProperty}" FontSize="20" Margin="10" Width="100" Height="30" />
</Grid>
</UserControl>
现在我想在子视图中指定Window
标题,因此我在DialogWindow
代码隐藏
public static readonly DependencyProperty DialogTitleProperty = DependencyProperty.RegisterAttached(
"DialogTitle",
typeof(string),
typeof(DialogWindow));
public static void SetDialogTitle(UIElement element, string value)
{
element.SetValue(DialogTitleProperty, value);
}
public static string GetDialogTitle(UIElement element)
{
return (string)element.GetValue(DialogTitleProperty);
}
并将其应用于子视图
<UserControl ...
local:DialogWindow.DialogTitle="My Title">
...
</UserControl>
并尝试绑定Window.Title
<Window ....
Title='{Binding Path=Content.(local:DialogWindow.DialogTitle), ElementName="myPresenter"}'>
...
</Window>
但它不起作用,因为ContentControl
的内容是视图模型本身,而不是DataTemplate定义的相应视图。
抛出异常:&#39; System.InvalidCastException&#39;在PresentationFramework.dll System.Windows.Data错误:17:无法获得&#39; DialogTitle&#39;来自&#39;内容&#39;的值(类型&#39;字符串&#39;) (键入&#39; TestViewModel&#39;)。 BindingExpression:路径=含量(0);的DataItem =&#39; ContentControl中&#39; (名称=&#39; myPresenter&#39);目标元素是&#39; DialogWindow&#39; (名称=&#39;&#39);目标财产是&#39;标题&#39; (type&#39; String&#39;)InvalidCastException:&#39; System.InvalidCastException:无法从ContentControlApplication.TestViewModel强制转换为System.Windows.DependencyObject。&#39;
如何绑定附加到从数据模板中即时创建的视图的属性?
已修改:已将MainWindow
重命名为DialogWindow
以清除示例意图,更正附加属性成员字段的名称以遵循指南。