WPF组合框并选择editem绑定到XML数据源
我在DataTemplate中有一个组合框,如下所示:WPF组合框并选择editem绑定到XML数据源,wpf,binding,combobox,Wpf,Binding,Combobox,我在DataTemplate中有一个组合框,如下所示: <ComboBox x:Name="cboImages" Grid.Row="1" Grid.Column="1" SelectedItem="{Binding XPath=ImageName, Path=SelectedItem.Content, Mode=TwoWay}" IsSynchronizedWithCurrentItem="True" > <ComboBoxItem>Image1.jpg</
<ComboBox x:Name="cboImages" Grid.Row="1" Grid.Column="1" SelectedItem="{Binding XPath=ImageName, Path=SelectedItem.Content, Mode=TwoWay}" IsSynchronizedWithCurrentItem="True" >
<ComboBoxItem>Image1.jpg</ComboBoxItem>
<ComboBoxItem>Image2.jpg</ComboBoxItem>
<ComboBoxItem>Image3.jpg</ComboBoxItem>
</ComboBox>
图1.jpg
图像2.jpg
图像3.jpg
我试图实现的是用comboxBox的SelectedItem
更新XML数据源的属性(ImageName)
以上代码有什么问题吗。
提前感谢。我建议将您的组合框移到DataTemplate之外,并在ItemTemplate内进行组合框自定义
<Window x:Class="BindXML.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Main Window" Height="400" Width="800">
<Window.Resources>
<DataTemplate x:Key="comboTemplate">
<TextBlock Text="{Binding XPath=@ImageName}" Width="70" />
</DataTemplate>
<XmlDataProvider x:Key="src" XPath="/Root">
<x:XData>
<Root xmlns="">
<Item ImageName="Image1.jpg" />
<Item ImageName="Image2.jpg" />
<Item ImageName="Image3.jpg" />
</Root>
</x:XData>
</XmlDataProvider>
</Window.Resources>
<DockPanel>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<ComboBox x:Name="cboImages1"
Grid.Row="0"
DataContext="{StaticResource src}"
ItemTemplate="{StaticResource comboTemplate}"
ItemsSource="{Binding XPath=Item}"
SelectedItem="{Binding XPath=ImageName, Path=SelectedItem.Content, Mode=TwoWay}"
IsSynchronizedWithCurrentItem="True" >
</ComboBox>
<ComboBox x:Name="cboImages2"
Grid.Row="1"
DataContext="{StaticResource src}"
ItemTemplate="{StaticResource comboTemplate}"
ItemsSource="{Binding XPath=Item}"
SelectedItem="{Binding XPath=ImageName, Path=SelectedItem.Content, Mode=TwoWay}"
IsSynchronizedWithCurrentItem="True" >
</ComboBox>
<Button Grid.Row="2" Click="Button_Click" />
</Grid>
</DockPanel>
</Window>
好的,我已经设法解决了这个问题,但现在我又遇到了另一个问题。我有三个组合框,显示来自同一源文件(xml)的图像。用户从每个组合框中选择图像作为选择1、2和3。我将这3个选项绑定到产品数据源(xml文件)中的三个不同字段(Logo1、Logo2、Logo3),但所有三个combooEx都以某种方式绑定在一起。如果我从选择项1中拾取图像,则其他两个组合框将使用选择项1进行更新。
private void Button_Click(object sender, RoutedEventArgs e)
{
XmlElement e1 = cboImages1.SelectedItem as XmlElement;
if ( e1 != null )
{
XmlAttribute result1 = e1.Attributes["ImageName"] as XmlAttribute;
if ( result1 != null )
{
string name1 = result1.Value;
}
}
XmlElement e2 = cboImages2.SelectedItem as XmlElement;
if ( e2 != null )
{
XmlAttribute result2 = e2.Attributes["ImageName"] as XmlAttribute;
if (result2 != null)
{
string name2 = result2.Value;
}
}
}