親のプロパティ(別のUCまたはウィンドウでもよい)に基づいてソースを変更したい画像を含む単純なユーザーコントロールがあります。 UCの単純化されたバージョンは、このwpfのユーザーコントロールを親のプロパティにバインドする
<UserControl x:Class="Test.Controls.DualStateButton" ... x:Name="root">
<Grid>
<Image Height="{Binding Height, ElementName=root}" Stretch="Fill" Width="{Binding Width, ElementName=root}">
<Image.Style>
<Style TargetType="{x:Type Image}">
<Setter Property="Source" Value="{Binding ImageOff, ElementName=root}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding State}" Value="True">
<Setter Property="Source" Value="{Binding ImageOn, ElementName=root}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
</Grid>
</UserControl>
身長のように見える、幅、ImageOff、IMAGEON、そして国家はUC上のすべての依存関係プロパティです。 UCにはDataContextが設定されていないため、親を継承する必要があります。私がしようとしているのは、UCのStateがWindowのDualStateプロパティにバインドされている次のようなものです。
<Window x:Class="Test.MainWindow" DataContext="{Binding RelativeSource={RelativeSource Self}}">
...
<Grid>
<local:DualStateButton State="{Binding DualState}" Height="100" ImageOff="{StaticResource ButtonUp}" ImageOn="{StaticResource ButtonDown}" Width="100"/>
</Grid>
</Window>
は、私が何を得る、しかし、「国家」プロパティは「オブジェクト」「」メインウィンドウ上で見つからないというエラーは」ので、結合取っているように見える 『文字通りなくUCの状態を』ウィンドウのDualStateプロパティに割り当てます。誰かが私が間違っていることについていくつかの洞察を発することができますか?
UCのStateプロパティをコードまたはXAML(bool値)のどちらかに設定すると、正常に動作します。状態DPは以下のように定義される。
public static readonly DependencyProperty StateProperty =
DependencyProperty.Register("State", typeof(bool), typeof(DualStateButton),
new PropertyMetadata(false));
public bool State
{
get { return (bool)GetValue(StateProperty); }
set { SetValue(StateProperty, value); }
}
これが機能するには、データ型がバインディングか何かである必要がありますか?
DualStateプロパティがありますか? DualStateはWindowのプロパティですか?それとも、他のビューモデルの所有物ですか? – loopedcode
FindAncestorを探す – Mafii
はい、DualStateはウィンドウのプロパティです。エラーは 'オブジェクト' '' MainWindow 'に' State 'プロパティが見つからないため、DataContextは正しいです(つまり、ウィンドウを見ています)。問題は、DualStateではなく 'State'を探していることです。 – user7134019