【问题标题】:DataTrigger type to textbox/checkbox/DataTrigger 类型为文本框/复选框/
【发布时间】:2023-03-22 01:04:01
【问题描述】:

我有一个 ItemsControl,我在其中显示不同的属性和值,一侧是名称,另一侧是 TextBox。 ItemsSource 是自定义类的对象集合,具有 Name、Value 和 PropertyType 属性(使用反射 propertyinfo)

现在我想通过检测属性是否为 bool 类型来改进这一点,例如,这将显示一个复选框而不是一个文本框。这可以使用 DataTrigger 吗?

我使用一个控件让它半工作,我根据类型将模板设置为文本框或复选框,但是当我尝试“制表符”到下一个文本框或复选框时,它会将具有首先是文本框/复选框,并且只有在另一个“选项卡”之后才会关注包含的文本框/复选框/..

因此,如果有人知道此问题的解决方案,将不胜感激!

【问题讨论】:

  • 我最近遇到了一个类似的问题,如果布尔为假,我想在控件中显示一个 TextBox,如果该布尔为真,则在其中显示一个 TextBlock。我将 TextBox 和 TextBlock 都放在了我想要显示的位置。然后,我将每个的 Visible 属性绑定到布尔值。如果您认为这将是您的 sltn,我可以发布代码。

标签: c# wpf reflection datatrigger


【解决方案1】:

使用您已有的解决方案,并将错误获得选项卡焦点的控件上的Focusable 属性设置为 false。

【讨论】:

  • 这正是我要找的东西,我怎么没见过这么简单的东西。非常感谢! :)
【解决方案2】:

您可以使用 DataTemplate 根据 Value 属性类型选择不同的 View。

查看:

<ItemsControl ItemsSource="{Binding Path=Options}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <DataTemplate.Resources>
                        <DataTemplate DataType="{x:Type System:Boolean}">
                            <CheckBox IsChecked="{Binding Path=.}"/>
                        </DataTemplate>
                        <DataTemplate DataType="{x:Type System:String}">
                            <TextBox Text="{Binding Path=.}"/>
                        </DataTemplate>
                    </DataTemplate.Resources>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Path=Name, Mode=OneWay}"/>
                        <ContentControl Content="{Binding Path=Value}"/>
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

视图模型:

public class MainViewModel
{
    public ArrayList Options { get; set; }

    public MainViewModel()
    {
        Options = new ArrayList();
        Options.Add(new TextProperty());
        Options.Add(new BoolProperty());
    }

}

public class TextProperty
{
    public string Name { get; set; }

    public string Value { get; set; }

    public TextProperty()
    {
        Name = "Name";
        Value = "Default";
    }
}

public class BoolProperty
{
    public string Name { get; set; }

    public bool Value { get; set; }

    public BoolProperty()
    {
        Name = "IsEnabled";
        Value = true;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    相关资源
    最近更新 更多