Thứ Năm, 28 tháng 10, 2010

Attribute ContentProperty trong WPF

Để khai báo một thuộc tính là nột dung của thẻ trong WPF ta sử dụng Attribute ContentProperty.

Ví dụ để thay đổi nội dung thẻ của Button là Text thay vì là Content.

    [ContentProperty("Text")]

    public class ImageTextButton:Button

    {

        public ImageTextButton()

        {

            DockPanel content = new DockPanel();

            Image icon = new Image();

            icon.Width = 16;

            icon.Height = 16;

            TextBlock text = new TextBlock();

 

            icon.Source = ImageProvider.Icon;

            text.SetBinding(TextBlock.TextProperty, new Binding("Text") { Source = this });

            content.Children.Add(icon);

            content.Children.Add(text);

 

            DockPanel.SetDock(icon, Dock.Left);

            Content = content;

        }

 

 

        public string Text

        {

            get { return (string)GetValue(TextProperty); }

            set { SetValue(TextProperty, value); }

        }

 

        // Using a DependencyProperty as the backing store for Text.  This enables animation, styling, binding, etc...

        public static readonly DependencyProperty TextProperty =

            DependencyProperty.Register("Text", typeof(string), typeof(ImageTextButton), new UIPropertyMetadata(""));

 

 

    }


Đối với button chuẩn thì nội dung thẻ Button có thể là kiểu dữ liệu gì cũng được nhưng ImageTextButton thì bắt buộc phải là kiểu chuỗi.

 

Không có nhận xét nào:

Đăng nhận xét