Проблема привязки в CustomControl - PullRequest
0 голосов
/ 08 марта 2012

Я написал CustomControl для WPF, который представляет собой просто ContentControl с ContentPresenter и кнопкой.

Вот шаблон элемента управления (находится в Themes / Generic.xaml):

<ControlTemplate TargetType="{x:Type local:TestControl}">
    <StackPanel Background="{TemplateBinding Background}">
        <ContentPresenter Content="{TemplateBinding Content}" />
        <Button Content="Next" IsEnabled="{TemplateBinding IsNextButtonEnabled}" />
    </StackPanel>
</ControlTemplate>

Вот управляющий код (TestControl.cs):

public class TestControl : ContentControl
{
    /// <summary>
    /// Identifies the IsNextButtonEnabled dependency property
    /// </summary>
    public readonly static DependencyProperty IsNextButtonEnabledProperty = DependencyProperty.Register(
        "IsNextButtonEnabled", typeof(bool), typeof(TestControl),
        new PropertyMetadata(true)
    );

    static TestControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(TestControl), new FrameworkPropertyMetadata(typeof(TestControl)));
    }

    /// <summary>
    /// Gets or sets the value indicating if the Next button of the control is enabled
    /// </summary>
    [BindableAttribute(true)]
    public bool IsNextButtonEnabled
    {
        get
        {
            return (bool)GetValue(IsNextButtonEnabledProperty);
        }
        set
        {
            SetValue(IsNextButtonEnabledProperty, value);
        }
    }
}

Я хочу связать значение IsNextButtonEnabled TestControl с другим элементом управления (например, CheckBox), который находится внутри Contentсамого TestControl.

Итак, я сделал это, и оно работает (когда я проверяю или сниму флажок CheckBox, кнопка включает или отключает себя правильно):

MainWindow.xaml

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication2"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <local:TestControl IsNextButtonEnabled="{Binding ElementName=cb, Path=IsChecked}">
            <CheckBox Name="cb" IsChecked="True" />
        </local:TestControl>
    </Grid>
</Window>

Но я хочу объявить свой TestControl в отдельном xaml-файле.Поэтому я сделал это, но это не работает:

MainWindow.xaml

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication2"
    Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <local:MyTestControl />
    </StackPanel>
</Window>

MyTestControl.xaml (MyTestControl.cs не изменяется):

<local:TestControl x:Class="WpfApplication2.MyTestControl"
                   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                   xmlns:local="clr-namespace:WpfApplication2"
                   IsNextButtonEnabled="{Binding ElementName=cb, Path=IsChecked}">
    <Grid>
        <CheckBox Name="cb" IsChecked="True" />
    </Grid>
</local:TestControl>

Во время выполнения в окне вывода я получаю следующее сообщение об ошибке:

System.Windows.Data Ошибка: 4: не удается найти источник для привязки со ссылкой «ElementName = cb».BindingExpression: Path = IsChecked;DataItem = NULL;Целевым элементом является MyTestControl (Name = '');Свойство target - IsNextButtonEnabled (тип Boolean)

Я не понимаю свою ошибку.Я что-то не так сделал?

Заранее спасибо.

1 Ответ

2 голосов
/ 08 марта 2012

попробуйте это, привяжите IsChecked флажка к IsNextButtonEnabled свойству

<ContentControl x:Class="WpfStackOverflowSpielWiese.TestControl"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                x:Name="control">

  <Grid>
    <CheckBox Name="cb"
              IsChecked="{Binding ElementName=control, Path=IsNextButtonEnabled}" />
  </Grid>
</ContentControl>

коду

public partial class TestControl : ContentControl
{
  public TestControl() {
    this.InitializeComponent();
  }

  /// <summary>
  /// Identifies the IsNextButtonEnabled dependency property
  /// </summary>
  public static readonly DependencyProperty IsNextButtonEnabledProperty = DependencyProperty.Register(
    "IsNextButtonEnabled", typeof(bool), typeof(TestControl), new PropertyMetadata(true));

  static TestControl() {
    DefaultStyleKeyProperty.OverrideMetadata(typeof(TestControl), new FrameworkPropertyMetadata(typeof(TestControl)));
  }

  /// <summary>
  /// Gets or sets the value indicating if the Next button of the control is enabled
  /// </summary>
  [Bindable(true)]
  public bool IsNextButtonEnabled {
    get { return (bool)this.GetValue(IsNextButtonEnabledProperty); }
    set { this.SetValue(IsNextButtonEnabledProperty, value); }
  }
}

надеюсь, это поможет

...