开发者

How to bind from a source property to a TARGET method

开发者 https://www.devze.com 2023-02-09 11:02 出处:网络
There are plenty of ways to bind a SOURCE method to target property, either by ValueConverter or by ObjectDataProvider. However, what if I want to have the binding affect the target METHOD?

There are plenty of ways to bind a SOURCE method to target property, either by ValueConverter or by ObjectDataProvider. However, what if I want to have the binding affect the target METHOD?

Consider the following example:

class ListBoxViewModel
{
        public static readonly DependencyProperty CurrentItemProperty = DependencyProperty.Register("CurrentItem", typeof (object), typeof (ListBoxViewModel));

        public object CurrentItem
        {
            get { return (object) GetValue(CurrentItemProperty); }
            set { SetValue(CurrentItemProperty, value); }
        }   
}

I'd like to bind the property CurrentItem to ListBox's CollectionView. However, since the CurrentItem property of CollectionView is read-only, I can't bind to it directly. Instead, I have to execute MoveCurrentToPosition function. How can I do it?

If there is a different开发者_如何学Python way to do that - Without binding to a method, I'd love to hear it too, however, the main question is how to bind to a method, if not in this case, then in a similar one. If it is impossible, what is the best alternative? E.g one idea that comes to mind is subscribing to the change notification of the dependency property (CurrentItem in this case) and running the procedural code from that function.

Thanks!


You can register your property with a property changed callback in which you then can update the CollectionView manually:

public static readonly DependencyProperty CurrentItemProperty =
    DependencyProperty.Register
    (
        "CurrentItem",
        typeof(object),
        typeof(ListBoxViewModel),
        new UIPropertyMetadata(null, CurrentItemChanged)
    );
public object CurrentItem
{
    get { return (object)GetValue(CurrentItemProperty); }
    set { SetValue(CurrentItemProperty, value); }
}

private static void CurrentItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    // Update current item logic
}
0

精彩评论

暂无评论...
验证码 换一张
取 消