如何创建一个WPF用户控件与名为内容 [英] How to create a WPF UserControl with NAMED content
问题描述
我有与在以同样的方式不断重复使用附着的命令和逻辑的一组的控制。我决定创建一个包含所有常见的控制和逻辑的用户控件。
I have a set of controls with attached commands and logic that are constantly reused in the same way. I decided to create a user control that holds all the common controls and logic.
不过,我还需要控制才能够认为可以命名的内容。我试过如下:
However I also need the control to be able to hold content that can be named. I tried the following:
<UserControl.ContentTemplate>
<DataTemplate>
<Button>a reused button</Button>
<ContentPresenter Content="{TemplateBinding Content}"/>
<Button>a reused button</Button>
</DataTemplate>
</UserControl.ContentTemplate>
不过似乎放在用户控件中的任何内容不能被命名。例如,如果我用的控制方式如下:
However it seems any content placed inside the user control cannot be named. For example if I use the control in the following way:
<lib:UserControl1>
<Button Name="buttonName">content</Button>
</lib:UserControl1>
我收到以下错误:
I receive the following error:
无法设置名称属性值'BUTTONNAME
在元素按钮。 按钮是
下元件的范围
的UserControl1',它已经有了一个
当它在被定义的名字登记
另一个范围。
Cannot set Name attribute value 'buttonName' on element 'Button'. 'Button' is under the scope of element 'UserControl1', which already had a name registered when it was defined in another scope.
如果我删除了BUTTONNAME,然后再编译,但是我需要能够说出的内容。我怎样才能做到这一点?
If I remove the buttonName, then it compiles, however I need to be able to name the content. How can I achieve this?
推荐答案
这似乎是使用XAML时,这是不可能的。自定义控件似乎是一个矫枉过正的时候我居然有我需要的所有控制,但只需将它们分组连同逻辑的一个小一点,并允许指定的内容。
It seems this is not possible when XAML is used. Custom controls seem to be a overkill when I actually have all the controls I need, but just need to group them together with a small bit of logic and allow named content.
在 JD的博客作为 mackenir暗示,似乎有最好的折衷办法。扩展JD的解决办法,让仍然在XAML中定义的控件可能如下:
The solution on JD's blog as mackenir suggests, seems to have the best compromise. A way to extend JD's solution to allow controls to still be defined in XAML could be as follows:
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
var grid = new Grid();
var content = new ContentPresenter
{
Content = Content
};
var userControl = new UserControlDefinedInXAML();
userControl.aStackPanel.Children.Add(content);
grid.Children.Add(userControl);
Content = grid;
}
在我上面的例子我已经创建了一个名为UserControlDefinedInXAML用户控件是这样定义使用XAML任何普通用户控件。在我的UserControlDefinedInXAML我有一个叫StackPanel的在其中我希望我的命名内容出现aStackPanel。
In my example above I have created a user control called UserControlDefinedInXAML which is define like any normal user controls using XAML. In my UserControlDefinedInXAML I have a StackPanel called aStackPanel within which I want my named content to appear.
这篇关于如何创建一个WPF用户控件与名为内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!