UserControl中的依赖属性绑定 [英] Dependency Property Binding in UserControl
问题描述
public static DependencyProperty ListProperty = DependencyProperty.Register(
ItemsList,typeof(List< RequiredClass>),typeof(UsercontrolTest));
public List< RequiredClass> ItemList
{
get {return(List< RequiredClass>)GetValue(ListProperty); }
set
{
SetValue(ListProperty,value);
}
}
此属性绑定到我的viewmodel属性(ListOfItems)在xaml中:
< Window x:Class =TestProject.MainWindow
xmlns =http://
xmlns:x =http://schemas.microsoft.com/winfx/2006/xaml
xmlns:Test =clr-命名空间:TestProject
Title =MainWindowHeight =350Width =525>
< Grid>
< Grid.RowDefinitions>
< RowDefinition>< / RowDefinition>
< RowDefinition>< / RowDefinition>
< /Grid.RowDefinitions>
< Test:UserControlTest Grid.Row =0ItemsList ={Binding Path = ListOfItems}/>
< Button Grid.Row =1Content =AddItemsClick =Button_Click/>
< / Grid>
< / Window>
此外,我已经将codebehind中的窗口的数据文本初始化到viewmodel。问题是绑定从来没有似乎发生,set属性从不被调用为依赖属性。我在这里缺少一些东西?
这些getter和setter从未被绑定系统调用(因此你不应该放置其他代码那里)。该属性可能正在设置,但除非您在UserControl 的声明中执行某些操作,否则不会显示任何内容。例如
< UserControl Name =control...>
< ItemsControl ItemsSource ={Binding ItemsList,ElementName = control}/>
< / UserControl>
My solution is implemented in MVVM. The view is a window which hosts a usercontrol. I have created a dependency property for this userControl as below :
public static DependencyProperty ListProperty = DependencyProperty.Register(
"ItemsList", typeof(List<RequiredClass>), typeof(UsercontrolTest));
public List<RequiredClass> ItemsList
{
get { return (List<RequiredClass>)GetValue(ListProperty); }
set
{
SetValue(ListProperty, value);
}
}
This property is bound to my viewmodel property (ListOfItems) in xaml :
<Window x:Class="TestProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Test="clr-namespace:TestProject"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Test:UserControlTest Grid.Row="0" ItemsList="{Binding Path=ListOfItems}" />
<Button Grid.Row="1" Content="AddItems" Click="Button_Click" />
</Grid>
</Window>
Also I have initialized the datacontext of the window in codebehind to the viewmodel. Problem is the binding never seems to happen and the set property is never called for the dependency property. Am I missing something here?
Those getters and setters are never called by the binding system (hence you should never place additional code there). The property is probably being set but unless you do something with it in the declaration of the UserControl nothing will be displayed. e.g.
<UserControl Name="control" ...>
<ItemsControl ItemsSource="{Binding ItemsList, ElementName=control}" />
</UserControl>
这篇关于UserControl中的依赖属性绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!