我有一个具有多个用户控件的应用程序,这些用户控件在某些窗口中使用。其中一个用户控件定义此窗口中的所有其他用户控件是否应允许编辑,因此将所有IsEnabled
es False
es和{{1}的CheckBox
属性设置为ComboBox
}}秒。但是,Button
es应允许复制其文本,因此不应禁用,而只能禁用。
我尝试遍历TextBox
,但是一些自建的usercontrol没有任何属性可以禁用它们,但此usercontrol中包含的控件只是按钮和文本框。这就是为什么我尝试将样式应用于所有可变元素(LogicalTree
,CheckBox
,ComboBox
和Button
),但它不起作用。
在usercontrol的TextBox
部分,我定义了一些样式:
Ressources
在CodeBehind中,在检查条件后,我尝试了以下内容:
<Style TargetType="Control" x:Key="disabledStyle">
<Setter Property="IsEnabled" Value="False" />
</Style>
<Style TargetType="TextBox" x:Key="readOnlyStyle">
<Setter Property="IsReadOnly" Value="True" />
</Style>
但什么都没发生。我究竟做错了什么?我应该采用不同的方式吗?
=编辑1 ============================================ ======================
我现在尝试了以下内容,XAML:
# windowOwner is the root window containing this usercontrol
for control in [Button, ComboBox, CheckBox]:
if self.windowOwner.Resources.Contains(control):
self.windowOwner.Resources.Remove(control)
self.windowOwner.Resources.Add(control, self.Resources['disabledStyle'])
if self.windowOwner.Resources.Contains(TextBox):
self.windowOwner.Resources.Remove(TextBox)
self.windowOwner.Resources.Add(TextBox, self.Resources['readOnlyStyle'])
代码隐藏:
<Style x:Key="disabledStyle">
<!--<Setter Property="Button.IsEnabled" Value="False" />
<Setter Property="CheckBox.IsEnabled" Value="False" />-->
<Setter Property="ComboBox.IsEnabled" Value="False" />
<Setter Property="TextBox.IsReadOnly" Value="True" />
</Style>
令人惊讶的是,即使self.windowOwner.Style = self.Resources['disabledStyle']
属性仅设置为IsEnabled
,一切都被禁用。如果我只设置ComboBox
属性没有任何反应。有人可以解释一下吗?
=编辑2 ============================================ ======================
我现在也尝试使用转换器:
(XAML)
TextBox.IsReadOnly
(转换器)
<Style TargetType="Control" x:Key="disabledStyle">
<Setter Property="IsEnabled" Value="False" />
<!--<Setter Property="Button.IsEnabled" Value="False" />
<Setter Property="CheckBox.IsEnabled" Value="False" />
<Setter Property="ComboBox.IsEnabled" Value="False" /> -->
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource typeConverter}}" Value="True">
<Setter Property="IsEnabled" Value="True" />
<Setter Property="TextBox.IsReadOnly" Value="True" />
</DataTrigger>
</Style.Triggers>
</Style>
但同样,一切都被禁用(如果使用已注释的变体,则没有任何反应)。
我让它遍历可视树:
public class TypeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool res = value.GetType() == typeof(TextBox);
return res;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{ // Don't need any convert back
return null;
}
}
但我也希望以后能够将更改重置为原始状态。这意味着我必须保存所有更改,这使得这远远应该是复杂的。我没有想法。
答案 0 :(得分:2)
我不认为删除样式并添加新样式会通知控件应用新样式。
您应该直接在控件上设置样式,如:
self.MyControl.Style = self.Resources['readOnlyStyle'] as Style
语法可能不同,但我是一个c#guy。
答案 1 :(得分:2)
您可能无法使用www.$anything.example.com
获取资源(通常在控件层次结构中定义样式时执行此操作)。它可以给你null并且可能不会注意到它。
试
self.Resources['disabledStyle']
如果FindResource()找不到所请求的资源,则会给您错误。
答案 2 :(得分:2)
嗨,请尝试下一个:
<强> XAML 强>
<Window x:Class="ListViewWithCanvasPanel.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:listViewWithCanvasPanel="clr-namespace:ListViewWithCanvasPanel"
Title="MainWindow" Height="350" Width="525" x:Name="This" ResizeMode="CanResize"
listViewWithCanvasPanel:Attached.AreChildrenEnabled = "true"><!--put your content here--></Window>
附加属性代码
public class Attached
{
public static readonly DependencyProperty AreChildrenEnabledProperty = DependencyProperty.RegisterAttached("AreChildrenEnabled", typeof (bool), typeof (Attached), new PropertyMetadata(default(bool), AreChildrenEnabledPropertyChangedCallback));
private static void AreChildrenEnabledPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
{
var val = (bool) args.NewValue;
if (val == false)
{
var visual = dependencyObject as FrameworkElement;
if (visual == null) return;
visual.Loaded -= VisualOnLoaded;
visual.Unloaded -= VisualOnUnloaded;
}
else
{
var visual = dependencyObject as FrameworkElement;
if(visual == null) return;
visual.Loaded += VisualOnLoaded;
visual.Unloaded += VisualOnUnloaded;
}
}
private static void VisualOnUnloaded(object sender, RoutedEventArgs e)
{
var visual = sender as FrameworkElement;
if (visual == null) return;
visual.Loaded -= VisualOnLoaded;
}
private static void VisualOnLoaded(object sender, RoutedEventArgs routedEventArgs)
{
var visual = sender as FrameworkElement;
if (visual == null) return;
var list = visual.GetAllVisualChildren();
Debug.WriteLine("children count on loading: {0}", list.Count);
var actionOnChildrenLoading = GetActionOnEachLoadedVisualChild(visual);
if(actionOnChildrenLoading == null) return;
list.ForEach(o =>
{
var combo = o as ComboBox;
if (combo != null)
{
combo.IsEnabled = false;
}
var button = o as Button;
if (button != null)
{
button.IsEnabled = false;
}
var textBlock = o as TextBlock;
if (textBlock != null)
{
textBlock.IsEnabled = false;
}
var cb = o as CheckBox;
if (cb != null)
{
cb.IsEnabled = false;
}
var textBox = o as TextBox;
if (textBox == null) return;
textBox.IsEnabled = true;
textBox.IsReadOnly = true;
});
}
public static readonly DependencyProperty ActionOnEachLoadedVisualChildProperty = DependencyProperty.RegisterAttached(
"ActionOnEachLoadedVisualChild", typeof (Action<DependencyObject>), typeof (Attached), new PropertyMetadata(default(Action<DependencyObject>)));
public static void SetActionOnEachLoadedVisualChild(DependencyObject element, Action<DependencyObject> value)
{
element.SetValue(ActionOnEachLoadedVisualChildProperty, value);
}
public static Action<DependencyObject> GetActionOnEachLoadedVisualChild(DependencyObject element)
{
return (Action<DependencyObject>) element.GetValue(ActionOnEachLoadedVisualChildProperty);
}
public static bool GetAreChildrenEnabled(UIElement element)
{
return (bool) element.GetValue(AreChildrenEnabledProperty);
}
public static void SetAreChildrenEnabled(UIElement element, bool value)
{
element.SetValue(AreChildrenEnabledProperty, value);
}
}
帮助代码
public static class VisualTreeHelperExtensions
{
public static T FindParent<T>(this DependencyObject child) where T : DependencyObject
{
while (true)
{
//get parent item
DependencyObject parentObject = VisualTreeHelper.GetParent(child);
//we've reached the end of the tree
if (parentObject == null) return null;
//check if the parent matches the type we're looking for
T parent = parentObject as T;
if (parent != null)
return parent;
child = parentObject;
}
}
public static List<DependencyObject> GetAllVisualChildren(this DependencyObject parent)
{
var resultedList = new List<DependencyObject>();
var visualQueue = new Queue<DependencyObject>();
visualQueue.Enqueue(parent);
do
{
var depObj = visualQueue.Dequeue();
var childrenCount = VisualTreeHelper.GetChildrenCount(depObj);
for (int i = 0; i < childrenCount; i++)
{
var v = VisualTreeHelper.GetChild(depObj, i);
visualQueue.Enqueue(v);
}
resultedList.Add(depObj);
} while (visualQueue.Count > 0);
resultedList.RemoveAt(0);
return resultedList;
}
}
**简短说明:*
查找根的所有可视子项(例如窗口),扫描它们并根据子类型执行操作。
此致
答案 3 :(得分:2)
试试这个,
1.添加一个布尔属性,将CanUserEdit添加到usercontrol,该用户控件控制可在其他控件中编辑的内容。
2.在其他用户控件中添加datatrigger并绑定到CanUserEdit(2个数据触发器,1个用于组合框,另一个用于文本框)。
在其中定义没有key的UserControl标签。这样会影响该用户控件中存在的所有文本框和组合框。
你也将获得一个集中控制。
示例代码: -
在每个userControl中添加CanUserEdit依赖项属性。
//Replace MainUserControl with your control name
public static readonly DependencyProperty CanUserEditProperty =
DependencyProperty.Register("CanUserEdit", typeof(bool),
typeof(MainUserControl));
public bool CanUserEdit
{
get { return (bool)GetValue(CanUserEditProperty); }
set { SetValue(CanUserEditProperty, value); }
}
在包含文本框和组合框的UserControl中,您可以将以下代码添加到UserControl.Resources
<UserControl.Resources>
<Style TargetType="TextBox">
<Setter Property="IsReadOnly" Value="False"/>
<Style.Triggers>
<DataTrigger Binding="{Binding CanUserEdit}" Value="false">
<Setter Property="IsReadOnly" Value="True"/>
</DataTrigger>
</Style.Triggers>
</Style>
<Style TargetType="ComboBox">
<Setter Property="IsEnabled" Value="True"/>
<Style.Triggers>
<DataTrigger Binding="{Binding CanUserEdit}" Value="false">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</UserControl.Resources>
这会影响该控件中的所有组合框和文本框。
在主窗口中,您将每个UserControl的CanUserEdit属性绑定到UserControl的CanUserEdit属性,该属性具有编辑控制权。
示例(MainUserControl是具有文本框和组合框的控件):
<local:MainUserControl CanUserEdit="{Binding CanUserEdit,ElementName=CanUserEditControl}" />
现在你所要做的就是切换控制编辑的UserControl的CanUserEdit属性,并且所有控件都会受到影响。
答案 4 :(得分:1)
我让它以一种不那么优雅的方式工作,迭代所有控件并自己设置属性。在这样做的同时,我保存了关于我更改了哪些控件的信息,以便能够将UI重置为原始状态。我对此并不满意,但似乎有效。我本来希望设置和取消设置一些风格,但我没有办法这样做。
这是我最终使用的内容,但随时发布更好的内容。首先是禁用部分:
visited = set()
def disableControls(control):
visited.add(control)
for childNumber in xrange(VisualTreeHelper.GetChildrenCount(control)):
child = VisualTreeHelper.GetChild(control, childNumber)
# save the old state
if type(child) in [Button, ComboBox, CheckBox] and child.IsEnabled:
child.IsEnabled = False
self.disabledControls.add(child)
elif type(child) == TextBox and not child.IsReadOnly:
child.IsReadOnly = True
self.disabledControls.add(child)
elif child not in visited:
disableControls(child)
disableControls(self.windowOwner)
以下是将UI“重置”为原始状态的部分:
while self.disabledControls:
child = self.disabledControls.pop()
if type(child) in [Button, ComboBox, CheckBox]:
child.IsEnabled = True
elif type(child) == TextBox:
child.IsReadOnly = False
visited
- set只是一个局部变量,可以避免多次访问控件,这种情况很奇怪,例如对于一些网格。 disabledControls
- 集保存所有未禁用的控件,因此已被代码禁用,并且必须在UI重置为原始状态时重置。
答案 5 :(得分:1)
实现此方案的一种简单方法可能是通过发布者订阅者实现。通过绑定/将该属性分配给目标控件,可以轻松地将属性状态发布到其他用户控件并设置控件状态。 我通过MvvmLight Messenger实现了类似的场景,我甚至根据一些内部控制状态禁用了一些Ribbon命令。