【发布时间】:2011-08-05 23:07:36
【问题描述】:
我创建了一个用户控件,可重复用于不同的目的。我已经定义了一个包含 UIElement 的依赖属性,我将其呈现为用户控件中某个区域的内容。
我注意到当我使用这个控件时。并为 content 属性中的元素命名,它们在运行时总是显示为 null。
MyContainer.xaml:
<UserControl x:Class="BSSApp.UI.Tests.MyContainer" x:Name="userControl"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Border x:Name="LayoutRoot" Background="Green" CornerRadius="20" BorderBrush="#005500" BorderThickness="10">
<ContentPresenter Content="{Binding ElementName=userControl, Path=MyContent}" Margin="20"/>
</Border>
</UserControl>
MyContainer.xaml.cs
namespace BSSApp.UI.Tests
{
public partial class MyContainer : UserControl
{
public static readonly DependencyProperty MyContentProperty =
DependencyProperty.Register("MyContent",
typeof(UIElement),
typeof(MyContainer),
new PropertyMetadata(new Grid()));
public UIElement MyContent
{
get
{
return (UIElement)GetValue(MyContentProperty);
}
set
{
SetValue(MyContentProperty, value);
}
}
public MyContainer()
{
InitializeComponent();
}
}
}
以及使用类: UserControlContentBug.xaml:
<UserControl x:Class="BSSApp.UI.Tests.UserControlContentBug"
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:t="clr-namespace:BSSApp.UI.Tests"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<t:MyContainer>
<t:MyContainer.MyContent>
<Button Name="btnWithName" Click="btnWithName_Click">Click Me</Button>
</t:MyContainer.MyContent>
</t:MyContainer>
</Grid>
</UserControl>
以及后面的代码: UserControlContentBug.xaml.cs
namespace BSSApp.UI.Tests
{
public partial class UserControlContentBug : UserControl
{
public UserControlContentBug()
{
InitializeComponent();
}
private void btnWithName_Click(object sender, RoutedEventArgs e)
{
// this throws an exception
btnWithName.Tag=2;
}
}
}
所以有一个按钮的声明,名为“btnWithName”。该变量确实是在后面的代码中声明的,但它保持为空...仅当按钮在另一个用户控件的属性中声明时才会发生。
有人知道怎么解决吗?
谢谢
【问题讨论】: