我正在使用 Binding 来填充 ListView
和 Image
的内容。但是由于某种原因,图像无法通过绑定(bind)获得它的值(value)。
如果我像
<Image Source="/Images/LedGreen.png"/>
图像显示在它应该出现的位置,但是使用绑定(bind)只是用绑定(bind)参数替换相对地址并在构造函数中使用 PackUri 将值传递给他。
代码是:
<Window.Resources>
<CollectionViewSource
x:Key="DeviceList"
Source="{Binding Path=DiscoveredDevicesList}">
</CollectionViewSource>
</Window.Resources>
.
.
.
<ListView
Grid.Row="1"
Width="500"
HorizontalAlignment="Left"
Margin="10"
Grid.Column="1"
DataContext="{StaticResource DeviceList}"
ItemsSource="{Binding}">
<ListView.View>
<GridView>
<GridViewColumn Header="Device name" DisplayMemberBinding="{Binding Path=DeviceName}"/>
<GridViewColumn Header="Rssi" DisplayMemberBinding="{Binding Path=Rssi}"/>
<GridViewColumn>
<GridViewColumnHeader Content="GPS" />
<GridViewColumn.CellTemplate>
<DataTemplate>
<Grid>
<Image Source="{Binding Path=ImagePath}"/>
</Grid>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
相关属性(property)和指导员是:
public Uri ImagePath { get; set; }
public MainWindowViewModel()
{
ImagePath = new Uri("pack://application:,,,/Images/LedRed.png");
}
我猜是因为我正在使用 Window.Resources
我正面临这个问题。但是,在我擦掉它并以另一种方式进行之前,我想确保这不是一个愚蠢的错误。
谢谢。
最佳答案
属性 ImagePath
似乎位于窗口的 DataContext 中,即 MainWindowViewModel
。因此,您需要遍历窗口的 DataContext 才能进行绑定(bind)。
使用RelativeSource
获取窗口的DataContext:
<Image Source="{Binding Path=DataContext.ImagePath,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"/>
关于c# - 图像未绑定(bind)到资源。如何使用 Relativesource 进行绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22981352/