簡體   English   中英

WPF UserControl公開用於綁定的子控件的屬性

[英]WPF UserControl exposing properties of subcontrols for binding

我正在為我的應用程序開發自定義用戶控件。 此控件非常簡單。 它只是一個網格,在[0,0]中有一個復選框,在[0,1]中有一個TextBlock。 我對它在XAML中的設計方式沒有任何疑問。

但是,第二步給我帶來了一些麻煩。 我正在嘗試公開IsChecked布爾值? 子控件的一部分,該復選框是用於綁定到我的主窗體上的復選框,並且具有與TextBlock的Text屬性相同的想法。

我已經嘗試了幾種不同的方法來解決這個問題,但無濟於事。

這是我的一般代碼:

public partial class CDCheckBox : UserControl
{
    public bool? IsChecked
    {
        get { return chk.IsChecked; }
        set { chk.IsChecked = value; }
    }

    public string Text
    {
        get { return lbl.Text; }
        set { lbl.Text = value; }
    }

    public static readonly DependencyProperty IsCheckedProperty =
    DependencyProperty.Register(
        "IsChecked",
        typeof(bool?),
        typeof(CDCheckBox),
        new PropertyMetadata(default(bool?), OnItemsPropertyChanged));

    public static readonly DependencyProperty TextProperty =
    DependencyProperty.Register(
        "Text",
        typeof(string),
        typeof(CDCheckBox),
        new PropertyMetadata(default(string), OnItemsPropertyChanged));

    /*
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnNotify(string propName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    }
    */
    private static void OnItemsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        // AutocompleteTextBox source = d as AutocompleteTextBox;
        // Do something...
        //lbl.Text = e.NewValue.ToString();
    }

    /*
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnNotify(string propName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    }
    */

    public CDCheckBox()
    {
        InitializeComponent();
    }
}

當我運行上面的代碼時,沒有任何錯誤,但是綁定的數據沒有顯示在TextBlock控件中。 在編寫依賴項屬性之前進行嘗試時,它在XAML中給我一個錯誤,提示“無法在類型'CDCheckBox'的'IsChecked'屬性上設置'Binding'。只能在DependencyProperty上設置'Binding' DependencyObject。”

但是有趣的是,此錯誤並未出現在構造函數中,而是出現在我編寫的window_loaded方法中。 但是,這似乎是一條紅色的鯡魚,就像我注釋掉該代碼一樣,它仍然無法通過表格顯示XAMLParse錯誤。

根據我的評論,您可以嘗試設計具有所需屬性類型的現有控件的樣式。 例如,在自定義控件中,您具有可為null的布爾屬性和字符串屬性。 如果重新使用CheckBox控件,則該CheckBox已經具有可為空的布爾屬性( IsChecked )和對象屬性( Content ),可用於保存字符串。

您可以按照以下方式重新設置CheckBox控件的樣式並更改其模板以獲得所需的結果:

<Window x:Class="..."
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Window.Resources>
        <Style x:Key="MySuperCheckboxStyle"
               TargetType="{x:Type CheckBox}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type CheckBox}">
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition />
                                <ColumnDefinition />
                            </Grid.ColumnDefinitions>
                            <CheckBox Grid.Column="0"
                                      IsChecked="{TemplateBinding IsChecked}"
                                      Content="Whatever you need here" />
                            <TextBlock Grid.Column="1"
                                       Text="{TemplateBinding Content}" />
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>

    <StackPanel>
        <CheckBox IsChecked="True"
                  Content="Unstyled check box"
                  Margin="10" />
        <CheckBox Style="{StaticResource MySuperCheckboxStyle}"
                  IsChecked="True"
                  Content="Styled check box"
                  Margin="10" />
    </StackPanel>
</Window>

此處的關鍵是控件模板中使用的TemplateBinding綁定。 它們不像普通數據綁定那樣綁定到數據上下文,而是綁定到要模板化的控件的屬性。

每當您發現自己想要在WPF中創建自定義控件時,就值得探索一下是否可以采用現有控件並更改其外觀以適合您的需要,因為這通常比創建新控件要少(反之,則不是總是有可能重新利用現有控件的用途,尤其是在您需要其他行為的情況下。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM