不能使用自定义控件

本文关键字:自定义控件 不能 | 更新日期: 2023-09-27 18:33:18

我在 StackPanel 中有一个自定义控件

<Window x:Class="Video_Editor.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    xmlns:m="clr-namespace:Video_Editor">
<Grid>
    </StackPanel>
    <ScrollViewer Margin="10,40,10,10" Grid.Row="2" VerticalScrollBarVisibility="Auto">
        <StackPanel Name="stackPanel" >
            <m:CustomControl Name="testControl"/>
        </StackPanel>
    </ScrollViewer>
</Grid>

自定义控件当前不执行任何操作。

public class CustomControl: ItemsControl
{
}

我尝试在窗口的构造函数中执行此操作:

public MainWindow()
{
    InitializeComponent();
    testControl.Items.Add("item");
}

我收到错误"名称"testControl 在当前上下文中不存在。

不能使用自定义控件

您将不得不使用 x:Name,因为您是从另一个公开Name属性本身的FrameworkElement派生的。

如果FrameworkElement设置了其Name属性(ItemsControl似乎正在这样做),则无法在派生类型上声明 Name 属性,但可以使用 Xaml x:Name 属性,以便可以对Name进行修改并从代码隐藏进行访问

例:

    <StackPanel Name="stackPanel" >
        <m:CustomControl x:Name="testControl"/>
    </StackPanel>