c# - 图像未绑定(bind)到资源。如何使用 Relativesource 进行绑定(bind)

标签 c# wpf binding uri pack

我正在使用 Binding 来填充 ListViewImage 的内容。但是由于某种原因,图像无法通过绑定(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/

相关文章:

javascript - 将ajax中的复杂对象发送到MVC

c# - 在 Key => Value 中合并两个数组

c# - 如何获取存储在资源中的图像的 Uri

wpf - 绑定(bind)到 CompositeCollection 时,ComboBox 未选择正确的项目

c# - 如何在 C# Windows 窗体中修复 ListView 的列宽?

c# - 使用 LINQ to SQL 获取刷新的数据

c# - WPF slider thumb.DragCompleted

wpf - PRISM 应用程序的整体应用程序架构

c# - 如何将项目集合绑定(bind)到复选框列表框?

.net - WPF 在 TextBox 中混合绑定(bind)和固定文本