1
我有一個MVVM WPF項目中,我試圖用多轉換,應通過在DataContext(視圖模型)的屬性來設置自定義附加屬性的值與另一個自定義元素上的附加屬性。使用multibinding設置自定義的附加屬性在WPF
我可以將屬性綁定到直接使用XAML屬性語法的視圖模型,但我無法理解如何設置使用多轉換器附加屬性的值。
<StackPanel>
<StackPanel.Resources>
<example:HelpTextConverter x:Key="ConvertHelpText"></example:HelpTextConverter>
</StackPanel.Resources>
<!-- shows binding the help text properties directly to the ViewModel's property -->
<Border example:HelpTextProperties.HelpText="{Binding HelpText}"></Border>
<!--how to set the HelpText attached property as the result of passing the DataContext.HelpText and the HelpTextProperties.ShowHelpText property to the HelpTextConverter?-->
<Border>
<example:HelpTextProperties.HelpText>
<!--does not compile-->
</example:HelpTextProperties.HelpText>
</Border>
</StackPanel>
代碼例如下面的附加屬性和IMultiValueConverter。
class HelpTextProperties
{
public static readonly DependencyProperty ShowHelpTextProperty =
DependencyProperty.RegisterAttached("ShowHelpText", typeof(bool), typeof(HelpTextProperties),
new UIPropertyMetadata(false));
public static bool GetShowHelpText(UIElement target)
{
return (bool)target.GetValue(ShowHelpTextProperty);
}
public static void SetShowHelpText(UIElement target, bool value)
{
target.SetValue(ShowHelpTextProperty, value);
}
public static readonly DependencyProperty HelpTextProperty =
DependencyProperty.RegisterAttached("HelpText", typeof(LabelVM), typeof(HelpTextProperties),
new UIPropertyMetadata(null));
public static LabelVM GetHelpText(UIElement target)
{
return (LabelVM)target.GetValue(ShowHelpTextProperty);
}
public static void SetHelpText(UIElement target, LabelVM value)
{
target.SetValue(ShowHelpTextProperty, value);
}
}
class HelpTextConverter : IMultiValueConverter
{
/// <summary>
/// returns the label in values[0] if values[1] is true
/// </summary>
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
LabelVM labelVM = (LabelVM)values[0];
if (values[0] == DependencyProperty.UnsetValue) { return null; }
if (values[1] is bool)
{
if ((bool)values[1]) { return labelVM; }
}
return null;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
感謝您可以提供任何幫助!
我希望避免這條道路,但最終會最終的方式。 – eoldre
這是我知道做多綁定的方式......我測試和工程 –