我有一個簡單的用戶控件,其中包含一個圖像,其源代碼基於父級(可能是另一個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中的狀態綁定到窗口的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國家’從字面上,而不是將其分配給Window的DualState屬性。有人能夠對我在做什麼錯了一些見解嗎?
如果我通過代碼或XAML(作爲布爾值)在UC上設置狀態屬性,它工作正常。國家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是窗口的屬性。由於錯誤顯示'State'屬性沒有在'對象'''MainWindow'上找到,因此DataContext是正確的(即,它正在查看窗口)。問題在於它尋找的是'國家'而不是'雙重國家' – user7134019