I am using Binding to fill the contents of a ListView
and also an Image
. However for some reason the Image doesn't get it's value through binding.
If I go like
<Image Source="/Images/LedGreen.png"/>
The image shows up where it should be, however using binding with just substituting the Relative address with a binding argument and handing him the value using a PackUri in the constructor doesn't.
The code is:
<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>
and the relative property and instructors are:
public Uri ImagePath { get; set; }
public MainWindowViewModel()
{
ImagePath = new Uri("pack://application:,,,/Images/LedRed.png");
}
I am guessing since I am using Window.Resources
I am facing this problem. However I want to make sure it's not a silly mistake before I scrub it off and do it the other way.
Thanks.
Property ImagePath
seems to be located in window's DataContext i.e. MainWindowViewModel
. So, you need to traverse to window's DataContext for binding to work.
Use RelativeSource
to get the window's DataContext:
<Image Source="{Binding Path=DataContext.ImagePath,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"/>