我有一組控件,附帶的命令和邏輯不斷以相同的方式重用。我決定創建一個擁有所有常用控件和邏輯的用戶控件。如何使用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