views:

351

answers:

2

Hi!

I've written an UserControl whose DataContext contains a collection and an bool property. The collection is being displayed (and editited) within a data grid, which has custrom column templates. The DataContext of a control in a column is of course an item of the collection of the UserControl's DataContext. However I need to bind one property of the control in a column to the bool property of the UserControl's DataContext and not to the collection item.

Do you have any ideas on how to solve this?

Best Regards, Oliver

+2  A: 

I'm pulling this straight from my answer on another post

http://stackoverflow.com/questions/1189753/getting-at-the-parent-of-a-databound-object/1190234#1190234

Here's the code from the post that I think might pertain to what youre trying to do:

<ListBox Name="list" ItemsSource="{Binding Items}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding}"/>
                <ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}, Path=DataContext.Values}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Basically the DataContext of the ListBox in this case contains a few lists and a combobox within the DataTemplate of the ItemTemplate is bound to a different member of the DataContext of the ListBox while the ItemsSource is bound to the Items member of DataContext. I would think this could apply to your DataGrid and column templates.

Mark Synowiec
A: 

Solution 1. Create a custom class which contains the collection and a bool property and set the DataContext to an instance of that class.

Solution 2. Set the user control's DataContext to the collection and add a bool property to your user control.

XAML:

<UserControl x:Class="DataContextDemo.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="self">
    <StackPanel>
        <ListBox ItemsSource="{Binding}" />
        <CheckBox IsChecked="{Binding Path=MyBoolProp, ElementName=self}" />
    </StackPanel>
</UserControl>

Code behind:

using System.Windows;
using System.Windows.Controls;

namespace DataContextDemo
{
    public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();
        }

        public bool MyBoolProp
        {
            get { return (bool)GetValue(MyBoolPropProperty); }
            set { SetValue(MyBoolPropProperty, value); }
        }

        public static readonly DependencyProperty MyBoolPropProperty =
            DependencyProperty.Register("MyBoolProp", 
                                        typeof(bool), 
                                        typeof(UserControl1), 
                                        new UIPropertyMetadata(true));
    }
}
Wallstreet Programmer