简体   繁体   中英

Binding the datacontext of a UserControl

Having work a bit and thanks to the answer I am now using :

public class PopupProgramazione : DependencyObject
    {
        public static readonly DependencyProperty ShowProperty = DependencyProperty.Register("FirstNo", typeof(bool), typeof(PopupProgramazione), null);

        public bool Show
         {
            get { return (bool)GetValue(ShowProperty); }
            set { SetValue(ShowProperty, value); }
         }
    }

in my view Model:

   public PopupProgramazione Popup
    {
        get { return _Popup; }
        set
        {
            _Popup = value;
            RaisePropertyChanged("Popup");
        }
    }

    public void Programmazione(InterventoSchedeConsuntivi intervento)
    {
        Popup.Show = true;
        InterventoPopupProgramazione = intervento;
    }

the strange problem comes with the xaml :

<local:PopupProgrammazione 
             x:Name="popupProg"
            Height="300" 
            Width="400"
            Canvas.ZIndex="2"
            Canvas.Left="150"
            Canvas.Top="150" Grid.RowSpan="4" Grid.Column="2" Margin="7,4,12,296"
            Visibility="{Binding Path=Popup.Show, Mode=TwoWay, Converter={StaticResource BoolToVisibilityConverter}}"
            DataContext="{Binding Path=InterventoPopupProgramazione}"
            >
        </local:PopupProgrammazione>

If I have only Visibility set it works well and I can see that I am getting through the converter using the debug.

If have both, then the initialisation of the popup is not made.( the popup is shown whereas Popup.Show=false). But If I close the popup :

private void Close_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.Visibility = Visibility.Collapsed;
        }

and then pass by my function to open it, it works but without passing by the converter.

Could someone explain me what is going on there?

[EDIT] Instead of binding specifically my usercontrol to a dedicated object, I use the datacontext of main xaml and then it works perfectly. [/EDIT]

You need to use a dependancy property

http://msdn.microsoft.com/en-us/library/ms752914.aspx

A decent tutorial http://www.switchonthecode.com/tutorials/wpf-tutorial-introduction-to-dependency-properties

basically you need to set up the static method ... this will register the property and let you bind to it in XAML. You then repoint your property to get and set the dependancy property for use in your code.

It looks a lot harder than it is ;)

Edit:

oh ... sorry maybe i misunderstood .. cant you just bind to the value that is in the viewmodel just like you did for showPopup? Failing that register with the property changed event?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM