[英]Image doesn't bind to the resource. How to use Relativesource for Binding
我正在使用Binding來填充ListView
和Image
。 但是由於某種原因,圖像無法通過綁定獲得價值。 如果我喜歡
<Image Source="/Images/LedGreen.png"/>
該圖像顯示了它應該在的位置,但是使用綁定僅將Relative地址替換為綁定參數,然后在構造函數中使用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>
相對財產和講師是:
public Uri ImagePath { get; set; }
public MainWindowViewModel()
{
ImagePath = new Uri("pack://application:,,,/Images/LedRed.png");
}
我正在猜測,因為我正在使用Window.Resources
所以我面臨着這個問題。 但是,我想確保這不是一個愚蠢的錯誤,然后再將其清除並以其他方式執行。
謝謝。
ImagePath
屬性似乎位於窗口的DataContext中,即MainWindowViewModel
。 因此,您需要遍歷window的DataContext才能進行綁定。
使用RelativeSource
獲取窗口的DataContext:
<Image Source="{Binding Path=DataContext.ImagePath,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"/>
這里的圖像數據上下文是DeviceList
,因為您將DeviceList
設置為列表視圖的日期上下文。 但是ImagePath在MainWindowViewModel
。 由於MainWindowViewModel
是Window中的數據上下文,因此您需要引用該數據上下文。
<Image Source="{Binding ImagePath, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.