自定义控件中的依赖项属性绑定和更新

时间:2011-01-18 19:09:03

标签: c# wpf xaml custom-controls dependency-properties

我创建了一个经历相同问题的代码的简化版本。问题是我不确定为什么我的自定义控件中的依赖属性在模型中被更改时不会更新。

型号:

public class MainWindowModel : INotifyPropertyChanged
{
    private bool isChecked;
    public bool IsChecked { get { return isChecked; } set { isChecked = value; OnPropertyChanged("IsChecked"); } }

    public event PropertyChangedEventHandler PropertyChanged;
    void OnPropertyChanged(string prop)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(prop));
    }
}

XAML:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:custom="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <custom:CustomTextbox x:Name="TextboxName" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" TextChanged="CustomTextbox_TextChanged">
        <custom:CustomTextbox.CustomTextboxItems>
            <custom:CustomTextboxItem IsChecked="{Binding IsChecked}" />
        </custom:CustomTextbox.CustomTextboxItems>
    </custom:CustomTextbox>

    <Button Content="Do It" Click="Button_Click" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="0,0,0,20" />
</Grid>
</Window>

代码背后:

public partial class MainWindow : Window
{
    MainWindowModel model;

    public MainWindow()
    {
        InitializeComponent();

        model = new MainWindowModel();
        this.DataContext = model;
    }

    private void CustomTextbox_TextChanged(object sender, TextChangedEventArgs e)
    {
        model.IsChecked = true;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if (TextboxName.CustomTextboxItems[0].IsChecked)
        {
            TextboxName.Text = "Property successfully changed";
        }
    }
}

自定义控制:

public class CustomTextbox : TextBox
{
    public CustomTextbox()
    {
        CustomTextboxItems = new ObservableCollection<CustomTextboxItem>();
    }

    public ObservableCollection<CustomTextboxItem> CustomTextboxItems { get; set; }
}

public class CustomTextboxItem : FrameworkElement
{
    public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register("IsChecked", typeof(bool), typeof(CustomTextboxItem), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

    public bool IsChecked
    {
        get { return (bool)GetValue(IsCheckedProperty); }

        set { SetValue(IsCheckedProperty, value); }
    }
}

正如您在自定义控件中看到的,我有一组项目,其中包含具有我想要绑定的依赖项属性的对象。所以我在xaml中创建对象并设置绑定,但是当我更新模型中的binded属性时,它不会在自定义控件中更改它。有什么想法吗?

1 个答案:

答案 0 :(得分:5)

在Visual Studio输出窗口中查找绑定错误。我想你会发现一些东西告诉你复选框上的绑定失败了。

您的CustomTextBox控件有一组CustomTextBoxItem个对象,您正在设置绑定。但是,您绝不会将这些项添加到逻辑树中。阅读我的帖子here,了解如何将这些项目添加到逻辑树中。