How to associate a field with a user control

In my 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 there is another window, I am trying to set the value for the last user control:

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

And this window in the download 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, the binding does not work. Do not transmit data. What am I wrong?

+5
source share
1 answer

You cannot snap to a field in WPF, you need to change listto a property.

You call a dependency property FooListin its UserControland ResultListin the Xaml, but I'm guessing that a typo in the question.

You must implement INotifyPropertyChangedin Windowso that the Bindings know that the value has been updated.

, DataContext, Xaml ProblemView, , Window ElementName

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

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
}
+1

All Articles