gpt4 book ai didi

c# - 如何使用自定义内容定义 UserControl?

转载 作者:太空宇宙 更新时间:2023-11-03 16:43:11 29 4
gpt4 key购买 nike

我想定义其中包含用户内容的自定义装饰器。但是当我尝试设置一些控件的名称时它总是失败。尝试这样做时我总是遇到此异常:

Cannot set Name attribute value 'butt' on element 'Button'. 'Button' is under the scope of element 'UserControl1', which already had a name registered when it was defined in another scope.

我不明白为什么会这样。这是代码:

<UserControl x:Class="WpfApplication5.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"
x:Name="control">
<ContentPresenter Content="{Binding ElementName=control, Path=DataContext}" />
</UserControl>

<Window x:Class="WpfApplication5.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication5"
Title="MainWindow" Height="350" Width="525">
<local:UserControl1>
<local:UserControl1.DataContext>
<Button x:Name="butt" />
</local:UserControl1.DataContext>
</local:UserControl1>
</Window>

如何正确地做到这一点?

最佳答案

您不能在 UserControls 中命名元素,有人认为这是一个错误,但我不知道是否是这种情况,无论哪种方式,这都行不通。您可以将 Button 声明为 Window 的资源,然后通过 StaticResource 插入它,但是该名称将不会注册为窗口类中的字段。

不管怎样,你真的需要这个名字吗?

编辑:另见 this question.

关于c# - 如何使用自定义内容定义 UserControl?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6796379/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com