Silverlight中的控制启用/禁用行为

时间:2012-04-16 10:10:37

标签: c# silverlight controls

我有一个包含很多文本框的应用程序。此文本框实际上从未被禁用,而是变为ReadOnly。我更喜欢将ContentControl的一个属性用于我的所有控件,但如果我将IsEnabled设置为false,则所有文本框都将被禁用。如何让它们进入只读模式?我不喜欢自己控制,也许我可以使用样式或其他东西重新分配行为?

编辑:我实际上正在寻找允许我通过绑定在一个地方使用绑定来绑定所有控件(IsReadOnly)状态的解决方案。像:

<ContentControl IsEnabled="{Binding boolFlag, Mode=OneWay}">
    <Grid x:Name="LayoutRoot" HorizontalAlignment="Stretch">
        ....
        <TextBox/>
    </Grid>
</ContentControl>

3 个答案:

答案 0 :(得分:2)

在您的情况下,使用DataForm控件似乎是最好的。它允许您作为一组控制其中的每个字段。它确实提供了IsReadOnly选项,还附带了许多非常好的免费功能。

此视频给出了很好的介绍

http://www.silverlight.net/learn/data-networking/data-controls/dataform-control

http://www.silverlightshow.net/items/Creating-Rich-Data-Forms-in-Silverlight-3-Introduction.aspx

http://www.silverlight.net/content/samples/sl4/toolkitcontrolsamples/run/default.html 寻找数据形式

干杯,

答案 1 :(得分:1)

我建议你为ContentControl使用一个简单的扩展方法来创建textBoxes IsReadOnly = True。例如:

public static class ContentControlEx
{
    public static void DisableTextBoxes(this ContentControl contentControl)
    {
        FrameworkElement p = contentControl as FrameworkElement;
        var ts = p.GetChildren<TextBox>();
        ts.ForEach(a => { if (!a.IsReadOnly) a.IsReadOnly = true; });
    }

    public static List<T> GetChildren<T>(this UIElement parent) where T : UIElement
    {
        List<T> list = new List<T>();
        int count = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < count; i++) {
            UIElement child = VisualTreeHelper.GetChild(parent, i) as UIElement;
            if (child != null) {
                if (child is T)
                    list.Add(child as T);

                List<T> l1 = GetChildren<T>(child);
                foreach (T u in l1)
                    list.Add(u);
            }
        }
        return list;
    }
}

用法(对于名称=“内容”的ContentControl):

content.DisableTextBoxes();

我有这样的XAML:

<Grid x:Name="LayoutRoot" Background="White">
    <ContentControl IsEnabled="True" Name="content">
        <StackPanel Margin="15">
            <TextBox Width="150" Name="tb1" Margin="5" Text="{Binding tb1}" />
            <TextBox Width="150" Name="tb2" Margin="5" Text="{Binding tb2}" />
            <TextBox Width="150" Name="tb3" Margin="5" Text="{Binding tb3}"/>
            <TextBox Width="150" Name="tb4" Margin="5" Text="{Binding tb4}"/>
            <Button Name="bSubmit" Click="bSubmit_Click">Make Textboxes readonly</Button>
        </StackPanel>
    </ContentControl>
</Grid>

如果有帮助,请告诉我......

答案 2 :(得分:0)

如果我理解正确,你想将每个TextBox.IsReadOnlyProperty绑定到一个bool。

你可以尝试这样的方式,类似于绑定IsEnabled的{​​{1}}属性的方式:

ContentControl

这可以为您提供所需内容:更改<TextBox IsReadOnly="{Binding boolFlag, Mode=OneWay}" ... /> <!-- in each of your textboxes --> ,每个文本框都会打开或关闭。