gpt4 book ai didi

WPF ComboBox 和 SelectedItem 绑定(bind)到 XML 数据源

转载 作者:行者123 更新时间:2023-12-02 04:15:24 25 4
gpt4 key购买 nike

我在 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</ComboBoxItem>
<ComboBoxItem>Image2.jpg</ComboBoxItem>
<ComboBoxItem>Image3.jpg</ComboBoxItem>
</ComboBox>

我想要实现的是使用 SelectedItem 更新我的 XML 数据源的属性 (ImageName)的组合框。

任何线索上面的代码有什么问题。
提前致谢。

最佳答案

我建议将您的 ComboBox 移到 DataTemplate 之外,并在 ItemTemplate 中进行 ComboBox 自定义。

<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>

以下测试代码隐藏显示了不同的 ComboxBox 选定项:
  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;
}
}
}

关于WPF ComboBox 和 SelectedItem 绑定(bind)到 XML 数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3110660/

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