【发布时间】:2012-06-11 21:07:28
【问题描述】:
我正在尝试使用我的 ViewModel 上设置为 Visibility 属性的属性动态隐藏扩展器上的切换按钮。至少这是我的想法。有没有办法只更改 ToggleButton 控件上的一个设置,而不必在我的 xaml 中执行 Toggle Button 的整个模板?
【问题讨论】:
我正在尝试使用我的 ViewModel 上设置为 Visibility 属性的属性动态隐藏扩展器上的切换按钮。至少这是我的想法。有没有办法只更改 ToggleButton 控件上的一个设置,而不必在我的 xaml 中执行 Toggle Button 的整个模板?
【问题讨论】:
您可以为Expander 使用Loaded 事件并在事件处理程序中设置Binding,或者如果您想要一种无需代码的可重用方式,您可以使用附加行为。
附加行为在Template 中找到ToggleButton,并将Binding 设置为附加属性ToggleButtonVisibility。
在此处上传了一个示例应用程序:ExpanderToggleButtonVisibilityTest.zip
这样使用
<Expander Name="expander"
behaviors:ExpanderBehavior.BindToggleButtonVisibility="True"
behaviors:ExpanderBehavior.ToggleButtonVisibility="{Binding YourVisibilityProperty}"
.../>
ExpanderBehavior
public class ExpanderBehavior
{
public static DependencyProperty BindToggleButtonVisibilityProperty =
DependencyProperty.RegisterAttached("BindToggleButtonVisibility",
typeof(bool),
typeof(ExpanderBehavior),
new PropertyMetadata(false, OnBindToggleButtonVisibilityChanged));
public static bool GetBindToggleButtonVisibility(Expander expander)
{
return (bool)expander.GetValue(BindToggleButtonVisibilityProperty);
}
public static void SetBindToggleButtonVisibility(Expander expander, bool value)
{
expander.SetValue(BindToggleButtonVisibilityProperty, value);
}
private static void OnBindToggleButtonVisibilityChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
Expander expander = target as Expander;
if (expander.IsLoaded == true)
{
BindToggleButtonVisibility(expander);
}
else
{
RoutedEventHandler loadedEventHandler = null;
loadedEventHandler = new RoutedEventHandler(delegate
{
BindToggleButtonVisibility(expander);
expander.Loaded -= loadedEventHandler;
});
expander.Loaded += loadedEventHandler;
}
}
private static void BindToggleButtonVisibility(Expander expander)
{
ToggleButton headerSite = expander.Template.FindName("HeaderSite", expander) as ToggleButton;
if (headerSite != null)
{
Binding visibilityBinding = new Binding
{
Source = expander,
Path = new PropertyPath(ToggleButtonVisibilityProperty)
};
headerSite.SetBinding(ToggleButton.VisibilityProperty, visibilityBinding);
}
}
#region ToggleButtonVisibilityProperty
public static DependencyProperty ToggleButtonVisibilityProperty =
DependencyProperty.RegisterAttached("ToggleButtonVisibility",
typeof(Visibility),
typeof(ExpanderBehavior),
new PropertyMetadata(Visibility.Visible));
public static Visibility GetToggleButtonVisibility(Expander expander)
{
return (Visibility)expander.GetValue(ToggleButtonVisibilityProperty);
}
public static void SetToggleButtonVisibility(Expander expander, Visibility value)
{
expander.SetValue(ToggleButtonVisibilityProperty, value);
}
#endregion // ToggleButtonVisibilityProperty
}
【讨论】:
OnApplyTemplate 中找到ToggleButton。我现在无法访问我的电脑,所以我不能举个例子,但你可以在这里找到类似的东西:stackoverflow.com/questions/5111756/…