Любой пример свойства зависимости в ViewModel? - PullRequest
2 голосов
/ 01 октября 2009

Может ли кто-нибудь привести пример свойства зависимости в ViewModel в WPF, который передается как datacontext для просмотра. Будет ли это требовать наследования от DependencyObject? Допустим, я хочу, чтобы ListBox SelectedItem был привязан к свойству Dependency CurrentItem во ViewModel. У меня это работает из оконного объекта, но то же самое не работает с ViewModel. В ViewModel я использую GetProperty и SetProperty, а не свойство CLR.

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>

Ответы [ 2 ]

4 голосов
/ 01 октября 2009

Хотя вы можете реализовать ViewModel как DependencyObject со свойствами зависимостей, большинство людей согласны с тем, что лучше использовать объект POCO, реализующий INotifyPropertyChanged ... Взгляните на эту статью Кента Boogaart для подробного сравнения двух подходов. Есть также ТАК вопрос об этом

1 голос
/ 01 октября 2009

Чтобы определить DependencyProperty в вашей модели представления, ваш класс модели представления должен быть производным от DependencyObject. В противном случае DependencyProperty не будет работать правильно.

Вам действительно нужно это свойство, чтобы быть DependencyPropety? Вы рассматривали реализацию INotifyPropertyChanged вместо?

...