gpt4 book ai didi

wpf - 如何在设计时解析 ContentControl ContentTemplateSelector?

转载 作者:行者123 更新时间:2023-12-01 14:35:35 29 4
gpt4 key购买 nike

为什么我无法在设计时解析 ContentControl ContentTemplateSelector?
(在运行时有效)
Designer(VS2010)显示异常:

System.Reflection.TargetInvocationException Exception has been thrown by the target of an invocation.

System.NullReferenceException Object reference not set to an instance of an object.

XAML:

<Window.Resources>
<DataTemplate x:Key="Temp1">
<TextBox TextWrapping="Wrap" Text="1" Height="20" Width="Auto"/>
</DataTemplate>

<local:TemplateSelector x:Key="mySelector"/>
<Grid>
<ContentControl ContentTemplateSelector="{StaticResource mySelector}">
<ContentControl.Content>
1
</ContentControl.Content>
</ContentControl>
</Grid>
</Window.Resources>

C#:

    public class TemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
//int num = int.Parse(item.ToString());
Window win = Application.Current.MainWindow;
return win.FindResource("Temp1") as DataTemplate;//load template based on num...
}

}

最佳答案

H.B. Application.Current.MainWindow 在设计时为 null 是正确的。这是按名称检索资源的更好方法:

public override DataTemplate SelectTemplate( object item, DependencyObject container ) {
var element = container as FrameworkElement;
if ( element != null ) {
var template = element.TryFindResource( "Temp1" ) as DataTemplate;
if ( template != null ) {
return template;
}
}
return base.SelectTemplate( item, container );
}

不过,您的代码的其他部分仍然不完整,所以我希望您已经完成了。例如,您的 DataTemplate 应该具有绑定(bind),而不是硬编码值。

关于wpf - 如何在设计时解析 ContentControl ContentTemplateSelector?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6178782/

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