【问题标题】:What is the difference between Control and ContentControl in Silverlight/WPF?Silverlight/WPF 中的 Control 和 ContentControl 有什么区别?
【发布时间】:2014-12-04 13:48:26
【问题描述】:

请解释 Control 和 ContentControl 之间的实际区别,因为谷歌搜索没有产生好的结果。

实际上,我面临一个与此相关的问题: 我有一个 Autocompletebox 控件继承自 ContentControl)。对于用户输入的新值,相应的属性的 Mode=TwoWay 工作正常,并且属性的值在 ViewModel 中得到更新,如果用户输入另一个新值,同样会重复。但如果用户再次输入之前输入的值,则不会更新属性的值。

所以我猜可能这个 Autocompletebox 控件 应该继承自 Control 类 而不是 ContentControl

我说的对吗?请添加您的意见和反馈。

编辑 - 添加伪代码::

控制类:-

public class MyAutoBox : ContentControl
{
    public int MyProp
    {
        get { return (int)GetValue(MyPropProperty); }
        set { SetValue(MyPropProperty, value); }
    }

    public static readonly DependencyProperty MyPropProperty =
      DependencyProperty.Register("MyProp", typeof(int), typeof(MyAutoBox), new PropertyMetadata(0));

}

ViewModel:-

public class MyViewModel : ViewModelBase, INavigationAware
{
    private int MyProp;

    public int MyProp
    {
        get { return MyProp; }
        set
        {
            if (MyProp != value)
            {
                MyProp = value;
                RaisePropertyChanged(() => MyProp);
            }
        }
    }

}

Xaml:

<MyControls:MyAutoBox Grid.Row="1"
                    Grid.Column="0"
                    Margin="10,0"
                    CanTypeIn="True"
                    MyProp="{Binding MyProp,  Converter={StaticResource NullToNumericConverter},Mode=TwoWay}"
<MyControls/>  

谢谢。

【问题讨论】:

  • 它不是 MS AutoCompleteBox。是我们开发的自定义控件,继承自ContentControl。

标签: c# .net wpf xaml silverlight


【解决方案1】:

ContentControl 实际上继承自 Control 类。因此,问题不会因此而出现。当属性值真正改变时,属性更改机制将起作用。如果新值和旧值相等,则不需要更新 ViewModel。

除此之外,Control 类是 WPF 中大多数 UI 元素的基类。它包含背景、前景、字体等属性。

ContentControl 是一个代表元素的类,它可以接受单个项目作为子元素。比如ListBoxItem、ComboBoxItem等就是ContentControls。

【讨论】:

  • 我举个例子,假设我输入了100,然后将其删除;然后输入 200、300,依此类推....直到此时它对每个这些值都可以正常工作。但是,如果我再次重复之前输入的任何值,比如 200,那么这次属性更改不会发生;由于我在 viewmodel 中的属性值没有得到更新。希望能解释清楚。
  • @xpertprogrammer 如果您可以在一些最小的示例代码中重现该问题,这将有很大帮助。
  • @McGarnagle 虽然我不能为您提供一个工作示例应用程序(因为它需要所有支持类、DLL 等),但我正在提供该类和 xaml 的伪代码并更新我的问题。请查看并提出建议。
  • @McGarnagle 嗨。你有没有通过代码?请提供您宝贵的意见。
猜你喜欢
  • 2010-11-20
  • 1970-01-01
  • 1970-01-01
  • 2010-11-21
  • 1970-01-01
  • 2014-06-28
  • 2010-11-23
  • 2012-09-04
  • 1970-01-01
相关资源
最近更新 更多