![](/img/trans.png)
[英]Changing WPF TreeView SelectedItem in SelectedItemChanged event
[英]SelectedItemChanged event for WPF custom TreeView control
C#、WPF。 我對 TreeView 控件進行了子類化,並且無法使SelectedItemChanged
事件正常工作。 我看不出我在做什么與this和this等示例不同。
代碼將運行,但在InitializeComponent()
我收到以下錯誤:
ArgumentException:無法綁定到目標方法,因為它的簽名或安全透明度與委托類型的不兼容。
這個最小的項目演示了這個問題:
<Window x:Class="TEST.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:custom="clr-namespace:TEST"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<custom:CustomTreeView x:Name ="treeViewConfig2"
SelectedItemChanged="TreeViewControl_SelectedItemChanged" />
</Grid>
</Window>
namespace TEST
{
/// <summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//CustomTreeView tree = new CustomTreeView();
}
}
public class CustomTreeView : TreeView
{
public CustomTreeView() { } // default constructor
private void TreeViewControl_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<Object> e)
{
// Do something
}
}
}
我想知道這是否與 Microsoft 文檔中提到的<object SelectedItemChanged="RoutedPropertyChangedEventHandler"/>
有關,但我不知道在哪里/如何實現它,並且在其他示例中沒有看到任何等效的東西。
將活動public
並不會改變行為。
問題只是由於將事件處理程序放在錯誤的 class 中造成的。 感謝 ASh 在評論中指出了這一點。 為了他人的利益,這是工作代碼:
<Window x:Class="TEST.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:custom="clr-namespace:TEST"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<custom:CustomTreeView x:Name ="treeViewConfig2"
SelectedItemChanged="TreeViewControl_SelectedItemChanged" />
</Grid>
</Window>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
CustomTreeView tree = new CustomTreeView();
}
private void TreeViewControl_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<Object> e)
{
MessageBox.Show((string)e.NewValue + " was selected");
}
}
public class CustomTreeView : TreeView
{
public CustomTreeView() {
Items.Add("Item 1");
Items.Add("Item 2");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.