我有一组控件,附带的命令和逻辑不断以相同的方式重用。我决定创建一个拥有所有常用控件和逻辑的用户控件。如何使用NAMED内容创建WPF UserControl
但是我还需要控件能够保存可以命名的内容。我尝试了以下内容:
<UserControl.ContentTemplate>
<DataTemplate>
<Button>a reused button</Button>
<ContentPresenter Content="{TemplateBinding Content}"/>
<Button>a reused button</Button>
</DataTemplate>
</UserControl.ContentTemplate>
但是,似乎放置在用户控件内的任何内容都无法命名。例如,如果我使用以下方式控制:
<lib:UserControl1>
<Button Name="buttonName">content</Button>
</lib: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,然后再编译,但是我需要能够名称内容。我怎样才能做到这一点?
这是一个巧合。我正要问这个问题!我也有同样的问题。将通用UI模式分解为UserControl,但希望通过名称引用内容UI。 – mackenir 2009-04-15 16:11:50
为什么不使用ResourceDictionary方法?在其中定义DataTemplate。或者使用BasedOn关键字继承该控件。只是我在做WPF代码隐藏UI之前要遵循的一些路径... – 2011-07-22 22:37:34
这个人发现了[解决方案](http://blog.bluecog.co.nz/archives/2007/08/27/wpf-cannot -set-name-attribute /)涉及摆脱他的自定义控件的XAML文件,并以编程方式构建自定义控件的UI。这个[博客文章](http://rrelyea.spaces.live.com/Blog/cns!167AD7A5AB58D5FE!2130.entry?wa=wsignin1.0&sa=752255111)在这个问题上有更多的话要说。 – mackenir 2009-04-15 16:43:08