Wpf 设置数据上下文
好吧,我现在就试着解释一下我的运动。。 这是我的PageOverzicht.xaml,这段代码很有效。它给了我一个下拉列表,里面有花的颜色(蓝色,橙色,白色,…)。现在,datacontext被硬编码以查找白色的花。 目标:通过代码隐藏设置datacontext,以便下一步可以使用selectionchanged属性选择具有选定颜色的花 所以现在我需要先设置datacontext,这样它就不会硬编码为白色。。 Listbox由xml节点组成,这些节点是使用PageOverzicht中的Page_加载方法的白色植物名称Wpf 设置数据上下文,wpf,data-binding,datacontext,xmldataprovider,Wpf,Data Binding,Datacontext,Xmldataprovider,好吧,我现在就试着解释一下我的运动。。 这是我的PageOverzicht.xaml,这段代码很有效。它给了我一个下拉列表,里面有花的颜色(蓝色,橙色,白色,…)。现在,datacontext被硬编码以查找白色的花。 目标:通过代码隐藏设置datacontext,以便下一步可以使用selectionchanged属性选择具有选定颜色的花 所以现在我需要先设置datacontext,这样它就不会硬编码为白色。。 Listbox由xml节点组成,这些节点是使用PageOverzicht中的Page_
<Page x:Class="Planten_BIS.PageOverzicht"
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"
xmlns:local="clr-namespace:Planten_BIS"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="PageOverzicht">
<Page.Resources>
<XmlDataProvider x:Key="CatalogDataSource" XPath="catalog" Source="data/catalogus.xml"></XmlDataProvider>
<DataTemplate x:Key="listItemTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Name="ImageName" Visibility="Collapsed" Text="{Binding XPath=botanical, StringFormat=images/{0}.jpg}" />
<Border BorderBrush="white" BorderThickness="2" CornerRadius="10" Background="{StaticResource AchtergrondKleur}">
<Rectangle Width="100" Height="100" RadiusX="10" RadiusY="10">
<Rectangle.Fill>
<ImageBrush ImageSource="{Binding Text, ElementName=ImageName}" />
</Rectangle.Fill>
</Rectangle>
</Border>
<StackPanel Orientation="Vertical" Margin="10" VerticalAlignment="Center">
<ListBoxItem Content="{Binding XPath=common}"/>
<ListBoxItem Content="{Binding XPath=price}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</Page.Resources>
<Grid>
<ListBox Name="ListboxFlowers" Background="Transparent" Foreground="white" DataContext="{Binding Source={StaticResource CatalogDataSource}, XPath=color[@name\=\'White\']/plant}" ItemsSource="{Binding}" ItemTemplate="{StaticResource listItemTemplate}"></ListBox>
</Grid>
</Page>
xml中数据来源的一小部分:
<?xml version="1.0" encoding="ISO8859-1" ?>
<catalog>
<color name="White">
<plant>
<common>Jacob's Ladder</common>
<botanical>Polemonium caeruleum i</botanical>
<zone>Annual</zone>
<light>Shade</light>
<price>$9.26</price>
<availability>022199</availability>
<color>white</color>
<description>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</description>
</plant>
雅各布的梯子
白头翁
年度
阴凉处
$9.26
022199
白色
知识是一种美德,是一种美德,是一种美德,是一种美德。但是,在最低限度上,我们需要一个实验室来进行日常工作。两人或两人在一个无教区的房间里互相指责。除偶尔因疏忽而死亡外,不得因疏忽而导致动物死亡。
框架为PageOverzicht的主窗口:
<Window x:Class="Planten_BIS.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:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
xmlns:local="clr-namespace:Planten_BIS"
mc:Ignorable="d"
Title="Plant Catalog" Height="600" Width="800">
<Window.Resources>
<Style x:Key="buttonStyle" TargetType="Button">
<Setter Property="Background" Value="{StaticResource ToolBarKleur}" />
<Setter Property="BorderBrush" Value="{StaticResource RandKleur}" />
<Setter Property="Foreground" Value="{StaticResource LetterKleur}" />
<Setter Property="Height" Value="30" />
<Setter Property="Margin" Value="6" />
</Style>
<Style x:Key="comboStyle" TargetType="ComboBox">
<Setter Property="Background" Value="{StaticResource ToolBarKleur}" />
<Setter Property="BorderBrush" Value="{StaticResource RandKleur}" />
<Setter Property="Foreground" Value="{StaticResource LetterKleur}" />
<Setter Property="Width" Value="100" />
<Setter Property="Height" Value="30" />
<Setter Property="Margin" Value="6" />
</Style>
<XmlDataProvider x:Key="CatalogDataSource" XPath="catalog" Source="data/catalogus.xml"></XmlDataProvider>
<CollectionViewSource x:Key="cvsColors" Source="{StaticResource CatalogDataSource}">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="color" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
<DataTemplate x:Key="comboItemTemplate">
<Label Content="{Binding XPath=@name}"/>
</DataTemplate>
</Window.Resources>
<DockPanel LastChildFill="True">
<ToolBar Background="{StaticResource ToolBarKleur}" DockPanel.Dock="Top">
<Button Style="{StaticResource buttonStyle}" Content="Backward"></Button>
<Button Style="{StaticResource buttonStyle}" Content="Forward"></Button>
<ComboBox Style="{StaticResource comboStyle}" SelectedIndex="0" ItemsSource="{Binding Source={StaticResource CatalogDataSource}, XPath=color}" ItemTemplate="{StaticResource comboItemTemplate}"></ComboBox>
</ToolBar>
<Frame Source="PageOverzicht.xaml" Name="frame" NavigationUIVisibility="Hidden">
<Frame.Background>
<ImageBrush ImageSource="assets/background.jpg" Stretch="UniformToFill"/>
</Frame.Background>
</Frame>
</DockPanel>
</Window>
数据源处理应该移动到一个控件,该控件是
组合框
和框架
的公共父控件,在这种情况下,我选择了主窗口
您应该将所需的DependecProperty
定义添加到主窗口中,该窗口可用于组合框.ItemsSource
,组合框.SelectedItem
和框架.DataContext
的数据绑定
对于XML处理,我将XMLDataProvider替换为XElement
数据源,该数据源允许LINQ转换为XML,以便在C#中轻松过滤或遍历XML对象树
现在,组合框
绑定到表示XMLcolor
节点的XElement
项的集合。所选的组合框
项是单个XMLcolor
元素。color
的后代plant
节点用于设置继承到页面的帧.DataContext
。页面中的列表框
现在将其项资源
直接绑定到数据上下文
,后者是主窗口。plantsofsselectedColor
属性。或者,例如,如果您需要将页面.DataContext
设置为不同的内容,您可以让绑定
遍历可视树,找到主窗口.PlantsOfSelectedColor
,使用相对资源查找或为列表框.ItemsSource的绑定.RelativeSource
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public static readonly DependencyProperty PlantColorNodesProperty = DependencyProperty.Register(
"PlantColorNodes",
typeof(IEnumerable<XElement>),
typeof(MainWindow),
new PropertyMetadata(default(IEnumerable<XElement>)));
public IEnumerable<XElement> PlantColorNodes
{
get => (IEnumerable<XElement>) GetValue(MainWindow.PlantColorNodesProperty);
set => SetValue(MainWindow.PlantColorNodesProperty, value);
}
public static readonly DependencyProperty SelectedPlantColorNodeProperty = DependencyProperty.Register(
"SelectedPlantColorNode",
typeof(XElement),
typeof(MainWindow),
new PropertyMetadata(default(XElement), OnSelectedPlantColorNodeChanged));
public XElement SelectedPlantColorNode
{
get => (XElement) GetValue(MainWindow.SelectedPlantColorNodeProperty);
set => SetValue(MainWindow.SelectedPlantColorNodeProperty, value);
}
public static readonly DependencyProperty PlantsOfSelectedColorProperty = DependencyProperty.Register(
"PlantsOfSelectedColor",
typeof(IEnumerable<XElement>),
typeof(MainWindow),
new PropertyMetadata(default(IEnumerable<XElement>)));
public IEnumerable<XElement> PlantsOfSelectedColor
{
get => (IEnumerable<XElement>) GetValue(MainWindow.PlantsOfSelectedColorProperty);
set => SetValue(MainWindow.PlantsOfSelectedColorProperty, value);
}
public MainWindow()
{
InitializeComponent();
// Open XML an collect all 'color' nodes
this.PlantColorNodes = XElement.Load("data/catalogus.xml").Elements("color");
}
private static void OnSelectedPlantColorNodeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var colorNode = e.NewValue as XElement;
// Get the 'plant' child nodes of the selected 'color' node
(d as MainWindow).PlantsOfSelectedColor = colorNode.Elements();
}
}
公共部分类主窗口:窗口
{
公共静态只读DependencyProperty PlantColorNodeProperty=DependencyProperty.Register(
“PlantColorNodes”,
类型(IEnumerable),
类型(主窗口),
新属性元数据(默认值(IEnumerable));
公共IEnumerable PlantColorNodes
{
get=>(IEnumerable)GetValue(MainWindow.PlantColorNodeProperty);
set=>SetValue(MainWindow.PlantColorNodeProperty,值);
}
公共静态只读DependencyProperty SelectedPlantColorNodeProperty=DependencyProperty.Register(
“SelectedPlantColorNode”,
类型(XElement),
类型(主窗口),
新的PropertyMetadata(默认值(XElement),OnSelectedPlantColorNodeChanged));
public XElement SelectedPlantColorNode
{
get=>(XElement)GetValue(主窗口。SelectedPlantColorNodeProperty);
set=>SetValue(MainWindow.SelectedPlantColorNodeProperty,值);
}
公共静态只读DependencyProperty PlantsOfSelectedColorProperty=DependencyProperty.Register(
“植物选择颜色”,
类型(IEnumerable),
类型(主窗口),
新属性元数据(默认值(IEnumerable));
选择颜色的公共IEnumerable植物
{
get=>(IEnumerable)GetValue(MainWindow.PlantsOfSelectedColorProperty);
set=>SetValue(MainWindow.PlantsOfSelectedColorProperty,value);
}
公共主窗口()
{
初始化组件();
//打开XML并收集所有“颜色”节点
this.PlantColorNodes=XElement.Load(“data/catalogs.xml”).Elements(“color”);
}
选定PlantColorNodeChanged上的私有静态无效(DependencyObject d、DependencyPropertyChangedEventArgs e)
{
var colorNode=e.NewValue作为XElement;
//获取所选“颜色”节点的“植物”子节点
(d作为主窗口)。PlantsOfSelectedColor=colorNode.Elements();
}
}
main window.xaml
<Window>
<DockPanel LastChildFill="True">
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=MainWindow}, Path=PlantColorNodes}"
SelectedItem="{Binding RelativeSource={RelativeSource AncestorType=MainWindow}, Path=SelectedPlantColorNode}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Attribute[name].Value}" />
</DataTemplate>
</ComboBox.ItemTemplate>
<ComboBox>
<Frame DatContext="{Binding RelativeSource={RelativeSource AncestorType=MainWindow}, Path=PlantsOfSelectedColor}"
Source="PageOverzicht.xaml" />
</DockPanel>
</Window>
<Page>
<ListBox ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate >
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Element[botanical].Value}" />
<TextBlock Text="{Binding Element[common].Value}"/>
<TextBlock Text="{Binding Element[price].Value}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Page>
PageOverzicht.xaml
<Window>
<DockPanel LastChildFill="True">
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=MainWindow}, Path=PlantColorNodes}"
SelectedItem="{Binding RelativeSource={RelativeSource AncestorType=MainWindow}, Path=SelectedPlantColorNode}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Attribute[name].Value}" />
</DataTemplate>
</ComboBox.ItemTemplate>
<ComboBox>
<Frame DatContext="{Binding RelativeSource={RelativeSource AncestorType=MainWindow}, Path=PlantsOfSelectedColor}"
Source="PageOverzicht.xaml" />
</DockPanel>
</Window>
<Page>
<ListBox ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate >
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Element[botanical].Value}" />
<TextBlock Text="{Binding Element[common].Value}"/>
<TextBlock Text="{Binding Element[price].Value}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Page>
您想要什么?当您说“我的应用程序的datacontext”时,您实际上是指应用程序,如应用程序的根元素,例如MainWindow,还是指