i have a problem moving a XMLDataprovider Binding with XPath from Xaml to code behind.
Labels.xml
<?xml version="1.0" encoding="utf-8" ?>
<Labels>
<btnOne Label="Button1"/>
<btnTwo Label="Button2"/>开发者_StackOverflow社区;
</Labels>
MainWindow.xaml
<Window
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" mc:Ignorable="d" x:Class="bindings.MainWindow"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<XmlDataProvider x:Key="XMLLabels" Source="Labels.xml" XPath="Labels"/>
</Window.Resources>
<Grid>
<Button Content="{Binding Source={StaticResource XMLLabels}, XPath=btnOne/@Label}" Height="23" HorizontalAlignment="Left" Margin="12,12,0,276" Name="btnOne" Width="75" />
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="93,12,0,276" Name="btnTwo" Width="75" Loaded="btnTwo_Loaded" />
</Grid>
</Window>
MainWindow.xaml.cs
...
private void btnTwo_Loaded(object sender, RoutedEventArgs e)
{
String Type = sender.GetType().Name;
if (Type == "Button")
{
Button btn = sender as Button;
Binding label = new Binding("XMLBind");
XmlDataProvider xmlLabels = (XmlDataProvider)this.FindResource("XMLLabels");
label.Source = xmlLabels;
label.XPath = "btnTwo/@Header";
btn.SetBinding(Button.ContentProperty, label);
}
}
...
The binding to content of btnOne works as aspected "Button1". But btnTwo is set to an empty string. The Output shows no errors.
Thanks for any advice.
shouldn't
label.XPath = "btnTwo/@Header";
be
label.XPath = "btnTwo/@Label";
精彩评论