Bind DataGrid Column to ViewModel Property
If I have the following DataGrid, how would I go about binding the Visibility of the TemplateColumn to a property on my ViewModel? The code I have here is based on a recommendation from this SO Question but no luck.
<sdk:DataGrid Visibility="{Binding GridVisible}" DataContext="{Binding}" Grid.Row="1" ItemsSource="{Binding Path=BookSource}" x:Name="bookGrid" AutoGenerateColumns="False" IsReadOnly="True">
<sdk:DataGrid.Columns>
<sdk:DataGridTemplateColumn Visibility="{Binding Path=DataContext.GridImgColumnVisible, ElementName=bookGrid}">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
开发者_如何学编程 <Image Stretch="Fill" Source="{Binding Path=SmallImgURI}"></Image>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
<sdk:DataGridTextColumn Header="Title" Width="*" Binding="{Binding CurrentBook.Title}" />
<sdk:DataGridTextColumn Header="Published" Width="150" Binding="{Binding CurrentBook.Published, StringFormat=d}" />
</sdk:DataGrid.Columns>
</sdk:DataGrid>
EDIT - I've also tried:
<sdk:DataGridTemplateColumn Visibility="{Binding Path=DataContext.GridImgColumnVisible, ElementName=root}">
and I've also added a button to my actual control, and bound its visibility to this property without difficulty.
It can be achieved in WPF, but Silverlight DataGrid is different. Visibility property isn't dependency property (you can't perform binding), Columns aren't belong to VisualTree and don't inherit DataContext.
Use code-behind, something like this:
var model = (MyViewModel)this.DataContext;
model.PropertyChanged += (s,e) =>
{
if(e.PropertyName == "GridImgColumnVisible")
this.UpdateGridColumnVisibility(model.GridImgColumnVisible);
};
public void UpdateGridColumnVisibility(Visibility imageVisibility)
{
var imgColumn = bookGrid.Columns.Cast<DataGridColumn>().FirstOrDefault(c => ((string)c.GetValue(Panel.NameProperty)) == "imgColumn");
if(imgColumn != null)
imgColumn.Visibility = imageVisibility;
}
And add the name to the column:
<sdk:DataGridTemplateColumn x:Name="imgColumn">
精彩评论