Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# wpf-can';不要使用自定义控件_C#_Wpf_Custom Controls - Fatal编程技术网

C# wpf-can';不要使用自定义控件

C# wpf-can';不要使用自定义控件,c#,wpf,custom-controls,C#,Wpf,Custom Controls,我在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" xm

我在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 MainWindow()
{
    InitializeComponent();
    testControl.Items.Add("item");
}

我收到一个错误“name”testControl在当前上下文中不存在。

您必须使用
x:name
,因为您是从另一个
FrameworkElement
派生的,该
FrameworkElement正在公开
name
属性本身

如果
FrameworkElement
设置了它的
Name
属性(这似乎是
ItemsControl
所做的),则不能在派生类型上声明
Name
属性,但可以使用
Xaml
x:Name
属性,这样就可以取消
Name
的权限并从代码隐藏处进行访问

例如:

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


你真的应该使用数据绑定而不是代码隐藏。顺便问一下,你的自定义控件是做什么的?@HighCore这只是一个例子。如果这个语句在这里不起作用,它在我需要它的地方就不会起作用。我的观点是,除非有充分的理由,否则通常不会对WPF控件进行子类化。同样,您应该真正使用数据绑定。如何声明
m
命名空间?发布完整的XAML。我刚刚用完整的XAML更新了这个问题
    <StackPanel Name="stackPanel" >
        <m:CustomControl x:Name="testControl"/>
    </StackPanel>