【发布时间】:2013-09-23 08:55:41
【问题描述】:
我有一个Grid 和其中的一个组件。
Grid 有一个自定义的DataContext,而孩子们必须使用默认的.xaml.cs 文件。
当然,更改父控件的DataContext 也会更改子控件。
所以我需要将孩子的DataContext 设置为xaml.cs 文件。
我正在尝试使用DataContext="{Binding}",但它不起作用。
我该怎么做?
编辑: 这是我基于回复的代码
<UserControl x:Class="MyNamespace.MyClass"
x:Name="MyName"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:lsp="clr-namespace:LSPlugins"
xmlns:utils="clr-namespace:LSPlugins.Utilities"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
d:DesignHeight="480" d:DesignWidth="480">
<UserControl.Resources>
<utils:ColorToSolidColorBrushValueConverter x:Key="ColorConverter"/>
<lsp:MyModel x:Key="MyModel" x:Name="MyModel"/>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" DataContext="{StaticResource MyModel}" Background="{Binding Path=BackgroundColor, Converter={StaticResource ColorConverter}}" Opacity="{Binding Path=BackgroundOpacity}">
<ContentPresenter Content="{Binding PresenterContent}" DataContext="{Binding ElementName=MyName}"/>
</Grid>
</UserControl>
我已经尝试过 Name 和 x:Name 但它仍然无法正常工作并且它会抛出这个异常:
System.Windows.Data 错误:BindingExpression 路径错误:在“MyNamespace.MyModel”“MyNamespace.MyModel”上找不到“PresenterContent”属性 (HashCode=63183526)。 BindingExpression: Path='PresenterContent' DataItem='MyNamespace.MyModel' (HashCode=63183526);目标元素是'System.Windows.Controls.ContentPresenter'(名称='');目标属性是“内容”(类型“System.Object”)..
【问题讨论】:
标签: c# xaml binding windows-phone-8 datacontext