2011-12-12 32 views
0

我想爲我的用戶控件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> 

+1

你的UC沒有IsChecked屬性 – 2011-12-12 16:52:34

+0

好吧,我剛找到解決方案。 IsChecked綁定在xaml文件中,我錯誤地使用了RelativeSource,我已經從高度和寬度屬性中複製並粘貼了,我只是修正了isChecked綁定,因此它是IsChecked =「{Binding ElementName = UC,Path = IsChecked} – Alex

+1

對不起,UC確實有一個IsChecked屬性,我在粘貼代碼時一定會忽略它。謝謝 – Alex

回答

0

好吧,我只是找到了解決辦法。對於xaml文件中的IsChecked綁定,我錯誤地使用了從高度和寬度屬性中複製並粘貼的RelativeSource。我剛剛修復了isChecked的綁定,所以它是IsChecked =「{Binding ElementName = UC,Path = IsChecked}它的工作原理 -