简体   繁体   中英

C# WPF: Dependency Property vs MVVM

I need to create a component with Dependency Property, I don´t know how to bind the data from another user control, can someone explain it to me? I don´t think i need to create a viewmodel for the component.

Here´s my code:

Here I call the component

    <DockPanel Grid.Row="1">
        <ctrls:CustomComboBox Collection="{Binding Path=TestingCollection}" SelectedCollectionItem="{Binding Path=SelectedItem}"
                              CreateCommand="" DeleteCommand="" UpdateCommand=""/>
    </DockPanel>

And Here it´s my component

        <ComboBox Grid.Column="0" SelectedValue="{Binding SelectedCollectionItem,ElementName=CustomComboBoxControl, Mode=TwoWay}"
                                  ItemsSource="{Binding Collection}" 
                                  DisplayMemberPath="Name"
                                  SelectedValuePath="Name"
                                  HorizontalContentAlignment="Center" 
                                  VerticalContentAlignment="Center"
                                  />

Here it is my xaml.cs

public static readonly DependencyProperty CollectionProperty =
    DependencyProperty.Register("Collection", typeof(ObservableCollection<object>), typeof(CustomComboBox));

public ObservableCollection<object> Collection
{
    get { return (ObservableCollection<object>)GetValue(CollectionProperty); }
    set { SetValue(CollectionProperty, value); }
}



public static readonly DependencyProperty SelectedCollectionItemProperty =
    DependencyProperty.Register("SelectedCollectionItem", typeof(object), typeof(CustomComboBox));
public object SelectedCollectionItem
{
    get { return (object)GetValue(SelectedCollectionItemProperty); }
    set { SetValue(SelectedCollectionItemProperty, value); }
}

EDIT:

I tryed creating a VM and setting the data context, and works, but dependency properties seem pointless

EDIT 2:

I succeded, i delete my VM i was lacking and ElementName in ItemSource

我成功了,我删除了我缺少的 VM 和 ItemSource 中的 ElementName

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