Question

So, I am trying to perform some databinding to a custom component that I have, but I can't seem to find any good information on how to do so. What I would like to do is just have the custom component in the main window to have a Bindning property...

<local:MultiColumnComboBox ItemsSource="{Binding Customers}" x:Name="NewCombo"></local:MultiColumnComboBox>

And then in custom component...

<DataGrid ItemsSource="{Binding ItemsSource}" Name="dataGrid"></DataGrid>

If anyone knows how to do this, some guidance would be appreciated :)

Edit

 public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(IList<Customer>), typeof(MultiColumnComboBox));
public MultiColumnComboBox()
{
    InitializeComponent();
}
//Items Source Binding
public IList<Customer> ItemsSource
{
    get 
    { 
        return (IList<Customer>)GetValue(ItemsSourceProperty); 
    }
    set 
    {
        System.Console.WriteLine("Binding");
        System.Console.WriteLine(value);
        SetValue(ItemsSourceProperty, value);
    }
}
Was it helpful?

Solution 2

I've figured it out!

All you have to do is use the DataContext property from the control so in your main page..

<local:custom control DataContext="{Binding Something}" />

And in your custom control, I bound...

ItemsSource="{Binding DataContext, ElementName=UOMControl}"

and that was it.

OTHER TIPS

I've gotten the Binding error you are seeing when I pass the wrong ownerType to DependencyProperty.Register method... please check to make sure you're using typeof(MultiColumnComboBox) as shown below.

/// <summary>
/// Interaction logic for MultiColumnComboBox.xaml
/// </summary>
public partial class MultiColumnComboBox : UserControl
{
    /// <summary>
    /// This creates the dependency property for the collection to display.
    /// </summary>
    public static readonly DependencyProperty ItemsSourceProperty =
        DependencyProperty.Register("ItemsSource", typeof(IList<Customer>), typeof(MultiColumnComboBox));

    /// <summary>
    /// This property gets you to the collection that's being displayed.
    /// </summary>
    public IList<Customer> ItemsSource
    {
        get { return (IList<Customer>)GetValue(ItemsSourceProperty); }
        set { SetValue(ItemsSourceProperty, value); }
    }

    public MultiColumnComboBox()
    {
        InitializeComponent();
    }
}

Also, make sure you set the Binding ElementName in your UserControl so that it has the right DataContext.

<UserControl x:Class="DependencyPropertyExample.MultiColumnComboBox"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             x:Name="userControl1">
    <Grid>
        <DataGrid ItemsSource="{Binding Path=ItemsSource, ElementName=userControl1}" />
    </Grid>
</UserControl>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top