数据绑定到图像源WPF时出现问题
我在数据绑定到数据绑定到图像源WPF时出现问题,wpf,image,data-binding,listview,Wpf,Image,Data Binding,Listview,我在数据绑定到图像的源属性时遇到一些问题 我有一个列表视图模板 <Style x:Key="ListViewStyle" TargetType="{x:Type ListView}"> <Setter Property="HorizontalContentAlignment" Value="Center"/> <Setter Property="Background" Value="Transparent" /> <Setter
图像
的源属性时遇到一些问题
我有一个列表视图
模板
<Style x:Key="ListViewStyle" TargetType="{x:Type ListView}">
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate x:Key="ListViewItemTemplate">
<StackPanel Width="60" Margin="5,5,10,5">
<Image Height="40" Width="40" Source="{Binding XPath=@Image}"
HorizontalAlignment="Center"/>
<TextBlock Text="{Binding XPath=@Name}" TextAlignment="Center"
TextWrapping="Wrap" FontWeight="bold"
HorizontalAlignment="Center" Margin="0,0,0,1" />
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
我已将此数据源分配为列表视图的项源
:
<ListView Name="MyListView" Style="{DynamicResource ListViewStyle}"
ItemTemplate="{StaticResource ListViewItemTemplate}"
ItemsSource="{Binding Source={StaticResource MyData},XPath=Item}"/>
我的问题是,当我运行应用程序ListViewItem
时,显示的是文本,但缺少Image
但当我在Window.Resource中定义了这个样式,并将样式用作StaticResource而不是动态资源时,一切正常
有谁能告诉我不拆散图像的原因吗?我希望全局使用此样式(因此我需要在ResourceDictionary中定义它)。有人能帮我吗?我想还没有人回答你的问题,因为我们看不出有什么问题
我决定尝试重现你的问题,但你的代码工作得很好,即使我尝试按照你的重现步骤
以下是我的步骤:
创建了一个空白的WPF应用程序
添加了一个资源字典文件Dictionary1.xaml
将
代码粘贴到
标记内的Dictionary1.xaml中
编辑掉在DataTemplate上设置x:键的打字错误
在Window1.xaml的顶部添加了
元素
将您的
代码粘贴到
标记中
替换图像路径名,例如image=“Resources\MenuIcons\Pic1.jpg”
变成image=“TestImage.jpg”
将您的
代码粘贴到
标记中
删除了伪ItemTemplate
值,假定这是旧代码遗留下来的
将字典“Dictionary1.xaml”合并到App.xaml中的应用程序字典中
以下是App.xaml中的相关标记:
<Application
...>
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Dictionary1.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
当我运行应用程序时,我看到一个列表框,其中包含下面有文本的图像
此时,我建议您尝试复制我的步骤,看看您的示例是否有效。如果是这样的话,试着慢慢地改变一些东西,使之像你的应用程序那样不起作用。在某个时刻,你会发现你的应用程序有什么不同之处。那么也许我们可以给你一些更好的建议如何修复它。嗯。。我发现了问题。。。问题是我的样式字典文件和图像位于项目目录中的两个独立目录中。我将所有字典文件保存在Styles目录中,将所有图像保存在Resources目录中,该目录位于Styles目录之外。
因此,我需要将xml中的图像路径更改为
<XmlDataProvider x:Key="MyData" XPath="/Reports">
<x:XData>
<Reports xmlns="">
<Item Name = "Item1" Image="..\Resources\MenuIcons\Pic1.png"/>
<Item Name = "Item2" Image="..\Resources\MenuIcons\Pic2.png"/>
<Item Name = "Item3" Image="..\Resources\MenuIcons\Pic3.png"/>
</Reports>
</x:XData>
</XmlDataProvider>
(我应该在路径之前添加..\n)这解决了我的问题。。感谢Ray Burns的回复Sasikumar D.R.0
<XmlDataProvider x:Key="MyData" XPath="/Reports">
<x:XData>
<Reports xmlns="">
<Item Name = "Item1" Image="..\Resources\MenuIcons\Pic1.png"/>
<Item Name = "Item2" Image="..\Resources\MenuIcons\Pic2.png"/>
<Item Name = "Item3" Image="..\Resources\MenuIcons\Pic3.png"/>
</Reports>
</x:XData>
</XmlDataProvider>