Oscar
Oscar

Reputation: 1147

How can I bind a field to a user control

In my user control I have this property:

    public static DependencyProperty FooListProperty = DependencyProperty.Register(
        "FooList", typeof(List<Problem>), typeof(ProblemView));

    public List<Problem> FooList
    {
        get
        {
            return (List<Problem>)GetValue(FooListProperty);
        }
        set
        {
            SetValue(FooListProperty, value);
        }
    }

    protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        base.OnPropertyChanged(e);

        if (e.Property == FooListProperty)
        {
            // Do something
        }
    }

And since another window, I´m trying to set a value for the last user control:

    <local:ProblemView HorizontalAlignment="Center"
                       VerticalAlignment="Center" FooList="{Binding list}" />

And that window in load contains:

    public List<Problem> list;

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        // Some processes and it sets to list field
        list = a;
    }

But in XAML code, binding it isn't working. Don't pass the data. What am I wrong?

Upvotes: 5

Views: 898

Answers (1)

Fredrik Hedblad
Fredrik Hedblad

Reputation: 84674

You can't bind to a Field in WPF, you'll have to change list to a property instead.

You call the Dependency Property FooList in your UserControl and ResultList in Xaml but I'm guessing that's a typo in the question.

You should implement INotifyPropertyChanged in the Window to let the Bindings know that the value has been updated.

I'm not sure if you have the correct DataContext set in the Xaml ProblemView, if you're unsure you can name the Window and use ElementName in the binding

<Window Name="window"
        ...>
    <!--...-->
    <local:ProblemView HorizontalAlignment="Center"
                       VerticalAlignment="Center"
                       ResultList="{Binding ElementName=window,
                                            Path=List}" />
    <!--...-->
</Window>

Sample code behind

public partial class MainWindow : Window, INotifyPropertyChanged
{
    //...

    private List<Problem> m_list;
    public List<Problem> List
    {
        get { return m_list; }
        set
        {
            m_list = value;
            OnPropertyChanged("List");
        }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #endregion
}

Upvotes: 1

Related Questions