【发布时间】:2015-01-26 20:13:00
【问题描述】:
我编写了自定义TreeView 控件。
XAML:
<TreeView x:Class="EArchiveMaster.View.MyTreeView"
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">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
<EventSetter Event="LostFocus" Handler="EventSetter_OnHandler" />
</Style>
</TreeView.ItemContainerStyle>
</TreeView>
.cs
public partial class MyTreeView
{
public event Action SomeItemLostFocus;
public MyTreeView()
{
InitializeComponent();
}
private void EventSetter_OnHandler(object sender, RoutedEventArgs e)
{
e.Handled = true;
if (SomeItemLostFocus != null)
SomeItemLostFocus();
}
}
但是当我尝试使用它时,我得到了众所周知的错误:
无法在元素“TextBox”上设置名称属性值“TextBox”。 “TextBox”在元素“MyTreeView”的范围内,当它在另一个范围内定义时,它已经注册了一个名称。
我找到了一些收据来解决这个错误。即,在其代码隐藏中指定控制的 .xaml 部分。 但我不知道我该怎么做。
【问题讨论】:
-
已经有一个相同的question for WPF。大多数答案也适用于您的情况。此外,您没有显示将
Name设置为TextBox的位置。 -
@icebat 我将
Name设置为TextBox的位置无关紧要。问题是“如何在其代码隐藏中指定控制的 .xaml 部分”。你能帮忙吗? -
@icebat 我已经看到了这个问题,但我不明白在我的情况下我应该在
OnInitialized方法中写什么......
标签: c# wpf xaml code-behind