簡體   English   中英

UserControl中的依賴項屬性綁定

[英]Dependency Property Binding in UserControl

我的解決方案是在MVVM中實現的。 該視圖是一個承載用戶控件的窗口。 我為此用戶控件創建了一個依賴項屬性,如下所示:

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);
    }
}

此屬性綁定到xaml中的viewmodel屬性(ListOfItems):

  <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>

我也已經在viewmodel的代碼后面初始化了窗口的datacontext。 問題在於綁定似乎從未發生過,並且從不為依賴屬性調用set屬性。 我在這里想念什么嗎?

綁定系統永遠不會調用這些getter和setter方法(因此,您永遠不要在此處放置其他代碼)。 該屬性可能已設置,但是除非您在UserControl聲明中對其進行任何操作,否則將不會顯示任何內容。 例如

<UserControl Name="control" ...>
    <ItemsControl ItemsSource="{Binding ItemsList, ElementName=control}" />
</UserControl>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM