可以在ViewModel中给出依赖属性的示例 [英] Can somone give example of Dependency Property in ViewModel

查看:166
本文介绍了可以在ViewModel中给出依赖属性的示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在WPF中的ViewModel中给出依赖属性的示例,以WPF方式传递,作为datacontext进行查看。这是否需要继承自DependencyObject?
说我希望ListBox SelectedItem绑定到ViewModel中的依赖属性CurrentItem。我有它从窗口对象工作,但同样的事情不能使用ViewModel。在ViewModel中,我使用GetProperty和SetProperty而不是CLR属性。

Can somone give example of Dependency Property in ViewModel in WPF passed as datacontext to view. Will this require inheriting from DependencyObject? Lets say I want ListBox SelectedItem bound to a Dependency Property CurrentItem in ViewModel. I have it working from window object but same thing donnt work with ViewModel . In ViewModel I use GetProperty and SetProperty and not CLR property.

public partial class Window1 : Window
{
    ObservableCollection<Person> persons;
    public ObservableCollection<Person> Persons
    {
        get
        {
            return persons;
        }
        set
        {
            persons = value;
        }
    }

    public static readonly DependencyProperty InfoTextProperty =
           DependencyProperty.Register(
           "InfoText",
           typeof(Person),
           typeof(Window1),
           new FrameworkPropertyMetadata(
               new PropertyChangedCallback(ChangeText)));

    public Window1()
    {
        InitializeComponent();
        this.DataContext = this;
        List<Person> people = new List<Person>();
        people.Add(new Person("Makeda Wilde"));
        people.Add(new Person(" Rosamaria Becnel"));
        people.Add(new Person("Jarrett Bernstein"));
        people.Add(new Person(" Leopoldo Palmer"));
        people.Add(new Person("Tyron Fisher"));
        people.Add(new Person(" Elba Kilpatrick"));
        people.Add(new Person("Ivory Lavender"));
        persons = new ObservableCollection<Person>(people);

        //persons.CollectionChanged += 
        //     new  System.Collections.Specialized.NotifyCollectionChangedEventHandler(
        //     persons_CollectionChanged);
    }

    void persons_CollectionChanged(object sender,  System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
    }

    public ListBoxItem InfoText
    {
        get
        {
            return (ListBoxItem)GetValue(InfoTextProperty);
        }
        set
        {
            SetValue(InfoTextProperty, value);
        }
    }


    private static void ChangeText(DependencyObject source, DependencyPropertyChangedEventArgs e)
    {
        Person newPerson = (Person)e.NewValue;
        newPerson.IsSelected = true;

        Person oldPerson = (Person)e.OldValue;
        if (oldPerson != null)
        {
            oldPerson.IsSelected = false;
        }
    }

    //  #region INotifyPropertyChanged Members
    //  event PropertyChangedEventHandler PropertyChanged;
    //   // Create the OnPropertyChanged method to raise the event
    //protected void OnPropertyChanged(string name)
    //{
    //    PropertyChangedEventHandler handler = PropertyChanged;
    //    if (handler != null)
    //    {
    //        handler(this, new PropertyChangedEventArgs(name));
    //    }
    //}


    //  #endregion
}

public class Person : INotifyPropertyChanged
{
    private bool isselected = false;
    public Person(string name)
    {
        this.Name = name;
        this.IsSelected = false;
    }

    public string Name { get; set; }
    public bool IsSelected
    {
        get
        {
            return isselected;
        }
        set
        {
            isselected = value;
            OnPropertyChanged("IsSelected");
        }
    }

    #region INotifyPropertyChanged Members
    public event PropertyChangedEventHandler PropertyChanged;
    // Create the OnPropertyChanged method to raise the event

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
    #endregion
}

<Grid>
    <ListBox Height="500"  Width="500" ItemsSource="{Binding Persons}"  Margin="104,46,212,0"  VerticalAlignment="Top"  SelectedItem="{Binding InfoText}"  >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Margin="2,2,2,2"  x:Name="tb" TextWrapping="Wrap" Text="{Binding Path=Name}"  />
                <DataTemplate.Triggers>
                    <DataTrigger Binding="{Binding Path=IsSelected}" Value="true">
                        <Setter Property="Background"  TargetName="tb" Value="Red"/>
                    </DataTrigger>
                </DataTemplate.Triggers>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>


推荐答案

尽管可以将ViewModel实现为 DependencyObject 具有依赖属性,大多数人都同意使用实现 INotifyPropertyChanged 的POCO对象更好...查看这篇文章。另外还有一个关于这个

Although you can implement a ViewModel as a DependencyObject with dependency properties, most people agree that it's better to use a POCO object implementing INotifyPropertyChanged... Have a look at this article by Kent Boogaart for a detailed comparison between the two approaches. There's also a SO question about this

这篇关于可以在ViewModel中给出依赖属性的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆