【问题标题】:Binding data to custom UserControl将数据绑定到自定义 UserControl
【发布时间】:2013-10-31 13:28:04
【问题描述】:

我想绑定 ObservableCollection 我的自定义 UserControl 但是当我想添加新元素并且我几乎完成但当我想添加新元素来收集我的应用程序时无缘无故崩溃。我想可能是变量不一致。但是我没有尝试使用对象/字符串/字符串。也许我一开始做错了什么?

自定义用户控件 XAML

<UserControl x:Class="backtrackPrototype.checklistItem"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    d:DesignHeight="80" d:DesignWidth="480">

    <Grid x:Name="LayoutRoot">
        <TextBlock 
            x:Name="label" 
            MaxHeight="407"  
            HorizontalAlignment="Left" 
            Margin="0,17,0,16" 
            VerticalAlignment="Center"
            Text="{Binding Path=Title, ElementName=checklistItem}"/>
        <CheckBox x:Name="checkbox" HorizontalAlignment="Right" VerticalAlignment="Center" Checked="checkbox_Checked" Unchecked="checkbox_Unchecked" />
    </Grid>
</UserControl>

自定义用户控件

public partial class checklistItem : UserControl 
{ 

      public string Title
      {
          get { return (string)this.GetValue(TitleProperty); }
          set { this.SetValue(TitleProperty, value); } 
      }

      // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
      public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(checklistItem), new PropertyMetadata(0));  

      public checklistItem() 
      {
            InitializeComponent();
      }

      public bool isChecked() 
      {
          if ((bool)checkbox.IsChecked) return true;
          return false;
      }

      private void checkbox_Checked(object sender, RoutedEventArgs e) 
      {
          //title.Foreground = Application.Current.Resources["PhoneAccentColor"];
          label.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
      }

      private void checkbox_Unchecked(object sender, RoutedEventArgs e) 
      {
          label.Foreground = new SolidColorBrush(Colors.White);
      }
}

主页中的 XAML

<ListBox Height="479" ItemsSource="{Binding}" x:Name="CheckList">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <local:checklistItem Title="{Binding Title}" Width="397"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox

主页中的 CS public ObservableCollection ListItems = new ObservableCollection();

ListItem item = new ListItem("Nowe",false);
ListItems.Add(item);
CheckList.DataContext = ListItems;

最后是列表

public class ListItem 
{
    public string Title { get; set; }
    public bool Checked { get; set; }

    public ListItem(string title, bool isChecked=false) 
    {
        Title = title;
        Checked = isChecked;
    }  
}

我需要一个能够以全新的眼光看待代码的人。谢谢。


更新:

还有什么要访问我的 CustomControl 中的控件,我在 that question 中使用第一个 anwser。 我还更新了我的 UserControl XAML。


更新 V2

当我使用 &lt;TextBox Title="{Binding Title}" Width="397"/&gt; insted 或 local:checklistItem 时,它工作得很好。


更新 V3

好吧,原来我没有向我的 UserControl 添加正确的 DataContext,所以现在 checklistItem 构造函数看起来像这样

public checklistItem() {
    InitializeComponent();
    this.DataContext = this;
}

并且控件添加正确,但现在标题绑定不起作用。因为当我对某些标题进行硬编码时,它可以正常工作,但不能绑定。但是相同的绑定适用于默认文本框。

【问题讨论】:

  • Ofc 我希望有一些明显的错误...我将使用try{}catch{}
  • 好吧,即使很明显你已经提供了一些代码,所以检查每一行都需要一些时间,更不用说没有 IDE 它可能真的无效。

标签: c# xaml data-binding windows-phone


【解决方案1】:

我认为您需要设置 itemsSource 而不是 DataContext。在 Listbox 上设置 DataContext 不会生成模板项

取出

ItemsSource="{Binding}"

来自 Xaml 并改变

CheckList.DataContext = ListItems;

CheckList.ItemsSource = ListItems;

【讨论】:

  • 哦,等等……我的错。它适用于文本框,但不适用于自定义 userControl :(
  • 另外从用户控件的TextBlock中取出ElementName=checkListItem。我刚刚对此进行了测试,效果很好。
  • 我删除它并将属性名称更改为 ItemName (标题道具,并且 listItem 中的标题令人困惑)。我照你说的做,但 atm 我得到了System.Windows.Data Error: BindingExpression path error: 'Title' property not found on 'backtrackPrototype.checklistItem' 'backtrackPrototype.checklistItem' (HashCode=30364973). BindingExpression: Path='Title' DataItem='backtrackPrototype.checklistItem' (HashCode=30364973); target element is 'backtrackPrototype.checklistItem' (Name=''); target property is 'ItemName' (type 'System.String')..
  • 我猜这个问题的根源是在 userControl 中设置this.DataContext = this。我删除它但现在System.Windows.Data Error: BindingExpression path error: 'ItemName' property not found on 'backtrackPrototype.ListItem' 'backtrackPrototype.ListItem' (HashCode=10896307). BindingExpression: Path='ItemName' DataItem='backtrackPrototype.ListItem' (HashCode=10896307); target element is 'System.Windows.Controls.TextBlock' (Name='label'); target property is 'Text' (type 'System.String')..
  • OK 代码中的所有标志都表明 UserControl 中的属性和 CustomClass 中的属性...因为现在它工作正常 :)
【解决方案2】:

我认为您在 XAML 中的绑定可能不正确。您在绑定中的元素名称是 LayoutRoot,这是您的网格的名称,而不是您的 UserControl。

它可能试图在 Grid 上找到它没有的名为 Title 的属性。

【讨论】:

  • 我已经更新了 xaml,但仍然没有。我正在尝试捕捉一些东西,但在 DataContext 上没问题。
猜你喜欢
  • 1970-01-01
  • 2011-03-17
  • 1970-01-01
  • 1970-01-01
  • 2013-01-20
  • 2012-02-09
  • 2012-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多