WPF自定义按钮 - 绑定动态和静态资源

时间:2016-10-21 05:09:13

标签: wpf binding

我想用样式(StaticResources)和图标(DynamicResources)创建我的按钮。我不知道,如何绑定资源。 StaticResource可以绑定为对象。 这是我的代码:

<Button x:Class="Spd.Client.View.Controls.IconButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" Style="{Binding ButtonStyle, UpdateSourceTrigger=PropertyChanged}">
    <StackPanel Orientation="Horizontal">
        <Rectangle Width="12" Height="12" Fill="{Binding Path=Foreground, 
                RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}">
            <Rectangle.OpacityMask>
                <VisualBrush Stretch="Fill" Visual="{Binding Icon, UpdateSourceTrigger=PropertyChanged}"/>
            </Rectangle.OpacityMask>
        </Rectangle>
        <TextBlock Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" FontSize="10" Margin="10 0 0 0"/>
    </StackPanel>
</Button>

代码背后:

   public partial class IconButton : Button, INotifyPropertyChanged
    {
        private string _text;

        public string Text
        {
            get { return _text; }
            set { _text = value; OnPropertyChanged(nameof(Text)); }
        }

        private object _style;

        public object ButtonStyle
        {
            get { return _style; }
            set { _style = value; OnPropertyChanged(nameof(Style));}
        }

        public ??? Icon //which datatype?
        {
            get { }
            set
            {

            }
        }

        public IconButton()
        {
            InitializeComponent();
            DataContext = this;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

使用:

    <controls1:IconButton Text="Click me!" ButtonStyle="{StaticResource DangerButton}" 
                          Icon="{DynamicResource appbar_user}"></controls1:IconButton>

1 个答案:

答案 0 :(得分:0)

很简单。不要太在意。

<Button Style={StaticResource ButtonStyle} Content={Binding Icon}>

此致

斯特芬