我正在尝试通过依赖项属性将传递的类型为“ CommandButton_VModel”的自定义对象绑定到User控件,但是似乎从未击中该dp的安装程序。我的意思是,在用户控件中,依赖项属性始终为null,有人可以告诉我我失败了吗?
下面是我的代码:
UserControl XAML:
<UserControl x:Class="FireAntTempConfigurer.UserControls.CommandButton_UC"
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"
xmlns:local="clr-namespace:FireAntTempConfigurer.UserControls"
xmlns:materialDesign="clr-namespace:MaterialDesignThemes.Wpf;assembly=MaterialDesignThemes.Wpf"
mc:Ignorable="d"
TextElement.Foreground="{DynamicResource MaterialDesignPaper}"
d:DesignHeight="60 " d:DesignWidth="60">
<Grid>
<Button Height="50" Padding="0,0,0,0" Margin="5" ToolTip="{Binding PlaceHolder}">
<Button.Content>
<materialDesign:PackIcon Kind="{Binding Icon}" Height="50" Width="50" />
</Button.Content>
</Button>
</Grid>
</UserControl>
后面的用户控制代码
public partial class CommandButton_UC : UserControl
{
public CommandButton_UC()
{
DataContext = CmdBtn;
InitializeComponent();
}
public CommandButton_VModel CmdBtn
{
get { return (CommandButton_VModel)GetValue(CmdBtnProperty); }
set { SetValue(CmdBtnProperty, value); }
}
public static readonly DependencyProperty CmdBtnProperty =
DependencyProperty.Register("CmdBtn", typeof(CommandButton_VModel), typeof(CommandButton_UC), new PropertyMetadata(default(CommandButton_VModel)));
}
MainWindow XAML:
<StackPanel>
<TextBlock>ToolBox:</TextBlock>
<Separator></Separator>
<StackPanel Orientation="Horizontal">
<cmdBtn:CommandButton_UC CmdBtn="{Binding MyProperty ,Mode=OneWayToSource}">
</cmdBtn:CommandButton_UC>
</StackPanel>
</StackPanel>
MainWindow代码
public partial class MainWindow : Window
{
public CommandButton_VModel MyProperty { get; set; }
public MainWindow()
{
MyProperty = new CommandButton_VModel { Icon = "Plus", PlaceHolder = "Add" };
DataContext = MyProperty;
InitializeComponent();
}
}
ViewModel
public class CommandButton_VModel : INotifyPropertyChanged
{
public string Icon { get; set; }
public string PlaceHolder { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public CommandButton_VModel()
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Icon"));
PropertyChanged(this, new PropertyChangedEventArgs("PlaceHolder"));
}
}
}
谢谢!