【问题标题】:Windows Universal UserControl BindingWindows 通用用户控件绑定
【发布时间】:2016-02-09 19:05:45
【问题描述】:

我为 Windows 通用应用创建了一个 UserControl。

我的代码后面的文件中有一个名为 HourList 的属性,因此定义...

internal ObservableCollection<int> HourList = 
     new ObservableCollection<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 
                           12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };

我想使用 HourList 将控件绑定到我的 UserControl 的 xaml 中,例如...

<ListView Width="100" ItemsSource="{Binding HourList, ElementName=timePicker}"
</ListView>

这假设我已经像这样命名了我的 UserControl...

<UserControl x:Name="timePicker"

但是,当我将控件放在页面上时,我的列表视图不包含我所期望的小时列表。

我错过了什么?

【问题讨论】:

  • 您需要设置数据上下文,ElementName 绑定在 IMO 中没有任何意义,但如果没有更多代码就很难判断
  • 就像@thumbmunkeys 提到的,需要更多关于您的用户控件的信息。由于您进行绑定的方式,HourList 需要您的 UserControl 上的属性或依赖项属性。如果您打算绑定到 UserControl 的数据上下文上的 HourList,请使用 DataContext.HourList 进行绑定。此外,将您的收藏设为公开,以便控件可以看到。

标签: c# xaml user-controls win-universal-app


【解决方案1】:

您可以简单地在用户控件的代码隐藏中创建一个属性:

public ObservableCollection<int> HourList
{
    get;
    set;
}
public UserControl()
{
    this.InitializeComponent();
    HourList = new ObservableCollection<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
    10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };                
}

但是在某些时候如果你需要绑定到它或者做动画,那么你需要它是一个像下面这样的依赖属性:

public static readonly DependencyProperty HourListProperty =
    DependencyProperty.Register("HourList",
    typeof(ObservableCollection<int>), typeof(MyUserControl1), 
    new PropertyMetadata(new ObservableCollection<int> 
    { 
      0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 
      14, 15, 16, 17, 18, 19, 20, 21, 22, 23 
    }));

public ObservableCollection<int> HourList
{
    get
    {
        return (ObservableCollection<int>)this.GetValue(HourListProperty);
    }

    set
    {
        this.SetValue(HourListProperty, value); 
    }
}

无论哪种方式 XAML 都是相同的:

<StackPanel>
    <UserControl x:Name="timePicker" />
        <ListView         
        Height="100"
        Foreground="Black"            
        Width="100" 
        ItemsSource="{Binding ElementName=timePicker, Path=HourList}">
        </ListView>
</StackPanel>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    • 2016-01-17
    • 2010-12-20
    • 1970-01-01
    • 2013-06-06
    • 1970-01-01
    相关资源
    最近更新 更多