Hi, I'm trying to create a button inside a column header and I'm facing binding problems. My code looks like this:
<telerik:RadGridView Name="RadGridView" CanUserSortColumns="False" ItemsSource="{Binding Stations}" IsFilteringAllowed="False" RowIndicatorVisibility="Collapsed" NewRowPosition="None" AutoGenerateColumns="False" IsReadOnly="True" ShowGroupPanel="False"> <telerik:RadGridView.SortDescriptors> <telerik:SortDescriptor Member="Number" SortDirection="Ascending" /> </telerik:RadGridView.SortDescriptors> <telerik:RadGridView.Columns> <telerik:GridViewDataColumn IsSortable="False"> <telerik:GridViewDataColumn.Header> <Button Style="{DynamicResource BorderlessButtonStyle}" Loaded="FrameworkElement_OnLoaded" BorderThickness="0" Click="ButtonBase_OnClick" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type telerik:RadGridView}},Path=DataContext.CopyCommand}" > </telerik:GridViewDataColumn.Header> ...But the command is never invoked due to this error:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='Telerik.Windows.Controls.RadGridView', AncestorLevel='1''. BindingExpression:Path=DataContext.CopyCommand; DataItem=null; target element is 'Button' (Name=''); target property is 'Command' (type 'ICommand')
I've tried with other Ancestor levels with no luck.
I tried to workaround this problem setting the command in the Loaded event of the button and it works, but I have a similar problem trying to set a Binding with a converter for Visibility in code behind:
private void FrameworkElement_OnLoaded(object sender, RoutedEventArgs e){ var button = (Button)sender; var viewModel = (TotalTideViewModel)this.DataContext; button.Command = viewModel.CopyCommand; var converter = new Converters.BooleanToVisibilityConverter(); button.SetBinding(VisibilityProperty, new Binding("DataContext.IsAnyRowSelected") { Converter = converter });}I've seen in another threads that you recommend to create a static resource with the view model, but we are working using our client's framework and we are not allowed to do that.
How can I create a proper binding?
Thanks,
Vicenc