gpt4 book ai didi

wpf - 在 ‘templated child element’内部访问父级属性的正确方法

转载 作者:行者123 更新时间:2023-12-03 10:37:22 25 4
gpt4 key购买 nike

我已经创建了模板,并且模板元素遍历到的不是逻辑层次结构而是物理层次结构,例如直接窗口,直接 View 。
这是为什么?在“模板子元素”内部访问父属性的正确方法是什么?

-查看型号代码

public MainViewModel()
{
if (IsInDesignMode)
{
Cars = new List<string>() { "Audi", "BMW", "Ferrari", "Ford" };
Models = new List<string>() { "Model 1", "Model 2" };
}
else
{
Cars = new List<string>() { "Audi", "BMW", "Ferrari", "Ford" };
Models = new List<string>() { "Model 1", "Model 2" };
}
}

public List<string> Models { get; private set; }

public List<string> Cars { get; private set; }

项目模板选择器
public class ComboBoxTemplateSelector : DataTemplateSelector
{
public override DataTemplate
SelectTemplate(object item, DependencyObject container)
{
var element = container as FrameworkElement;

var dataTemplate = element.FindResource(((item is string) && item.Equals("Ferrari")) ?
"DataTemplateTopLevelCombobox2" : "DataTemplateTopLevelCombobox1") as DataTemplate;

return dataTemplate;
}
}

-主要应用程式XAML程式码
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:proj="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525" DataContext="{Binding Main, Mode=OneWay, Source={StaticResource Locator}}">
<Window.Resources>
<ItemsPanelTemplate x:Key="ItemsPanelTemplateHorizontal">
<StackPanel IsItemsHost="True" Orientation="Horizontal"/>
</ItemsPanelTemplate>
<proj:QualityComboBoxTemplateSelector x:Key="QualityComboBoxTemplateSelector"/>
</Window.Resources>

<Grid>
<ComboBox HorizontalAlignment="Left" VerticalAlignment="Top" Width="120" Margin="87.2,44.8,0,0"
ItemsSource="{Binding Cars}"
ItemsPanel="{DynamicResource ItemsPanelTemplateHorizontal}"
ItemTemplateSelector="{StaticResource ComboBoxTemplateSelector}"
x:Name="CarsComboBox"/>
</Grid>
</Window>

资源字典
<DataTemplate x:Key="DataTemplateTopLevelCombobox1">
<Border BorderBrush="Black" BorderThickness="1" >
<TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding}" VerticalAlignment="Top"/>
</Border>
</DataTemplate>

<DataTemplate x:Key="DataTemplateTopLevelCombobox2">
<Border Width="100" >
<ComboBox Text="Custom" Height="21.96"
ItemsSource="{Binding DataContext.Models??"/>
</Border>
</DataTemplate>

最佳答案

我认为您实现FindResource的方式是正确的,因为FindeResource在树中遍历并使用指定的键搜索资源。 FindResource

But If you already know that your ResourceDictionary is Merged to App resources then you can access it directly like


App.Current.Resources["DataTemplateTopLevelCombobox2"]

万一您的ResourceDictionary合并到Window Resources,但FindResource不会合并,这将失败。

关于wpf - 在 ‘templated child element’内部访问父级属性的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20816204/

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