我正在尝试为我的用户控件ToggleImageButton创建一个名为IsChecked的依赖项属性。我只想在ToggleButton中设置并获取IsChecked属性。依赖项属性似乎不反映ToggleButton的IsChecked属性的实际值。请有人帮忙。
这是我的代码隐藏文件:
public partial class ToggleImageButton : UserControl
{
public ToggleImageButton()
{
InitializeComponent();
}
public ImageSource Image
{
get { return (ImageSource)GetValue(ImageProperty); }
set { SetValue(ImageProperty, value); }
}
public static readonly DependencyProperty ImageProperty =
DependencyProperty.Register("Image", typeof(ImageSource), typeof(ToggleImageButton), new UIPropertyMetadata(null));
public Boolean IsChecked
{
get { return (Boolean)GetValue(IsCheckedProperty); }
set { SetValue(IsCheckedProperty, value); }
}
}
这是xaml文件:
<UserControl x:Class="MyControls.ToggleImageButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Name="UC">
<Grid Margin="0,0,0,0">
<ToggleButton Margin="0,0,0,0" IsChecked="{Binding RelativeSource={RelativeSource Self}, Path=Source.IsChecked, Mode=TwoWay}">
<StackPanel Orientation="Horizontal" Margin="0,0,0,0">
<Image Source="{Binding ElementName=UC, Path=Image}"
Stretch="Fill"
Width="{Binding RelativeSource={RelativeSource Self}, Path=Source.PixelWidth}"
Height="{Binding RelativeSource={RelativeSource Self}, Path=Source.PixelHeight}"
Margin="0,0,0,0"/>
</StackPanel>
</ToggleButton>
</Grid>
答案 0 :(得分:0)
好的,我刚刚找到了解决方案。对于xaml文件中的IsChecked绑定,我错误地使用了从高度和宽度属性复制并粘贴的RelativeSource。我刚刚修复了isChecked绑定,因此它是IsChecked =“{Binding ElementName = UC,Path = IsChecked}并且它有效 -