【问题标题】:Custom control property - Binding problem自定义控件属性 - 绑定问题
【发布时间】:2011-03-04 16:25:33
【问题描述】:

当我使用我构建的一些简单的自定义控件时,我遇到了非常奇怪的问题: 这是自定义控制代码:

public partial class ToolButton : Button
{
    public string ToolID
    {
        get { return (string)GetValue(ToolIDProperty); }
        set { SetValue(ToolIDProperty, value); }
    }

   public static readonly DependencyProperty ToolIDProperty =
   DependencyProperty.Register("ToolID", typeof(string), typeof(ToolButton), new    UIPropertyMetadata(""));


    public ToolButton()
    {
        InitializeComponent();
    }
}

现在当我试图在主窗口中使用这个自定义控件时:

<ItemsControl Margin="100" ItemsSource="{Binding Path=Students}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                   <customControls:ToolButton Height="100" Width="100" Margin="10" Content="{Binding Value.Name}"/> 
                                 </DataTemplate>
             </ItemsControl.ItemTemplate>
        </ItemsControl>

而且绑定不起作用!!

但是当我使用简单的按钮时,绑定效果很好..

有人遇到过类似的问题吗??

谢谢...

【问题讨论】:

  • 这段代码不错,问题出在别处。粘贴执行绑定的代码。
  • 看看这个post是否有帮助。
  • 为什么类标记为partial? ToolButton 类有第二部分吗?如果是这样,您能否也发布该代码?
  • 这是vs2010暴露的默认自定义控件模板。类的其他部分没有实现(我的实现)
  • VS 不会为自定义控件生成第二部分(部分类)。不过,它适用于用户控件。并且您的控件应该是自定义控件。应该没有其他部分。所以只需删除控件的 .xaml 部分并删除 partial 关键字`。

标签: wpf binding


【解决方案1】:

将以下行放入 ToolButton 的构造函数中:

this.DataContext = this;

【讨论】:

  • 简单绑定失败的唯一原因(假设路径正确)是缺少上下文。
猜你喜欢
  • 2011-05-11
  • 2010-12-16
  • 2012-08-07
  • 1970-01-01
  • 1970-01-01
  • 2012-08-29
  • 1970-01-01
  • 2011-06-24
相关资源
最近更新 更多