c# - 是否可以在没有代码的用户控件中设置子控件属性?
问题描述
我有一个从某个地方抓到的示例 UserControl,我正在使用它来尝试了解 UserControls 的功能。我正在尝试做的是在窗口 xaml 中设置嵌入式控件的属性(例如,来自下面 UserControl 的 txtInput)。
我知道我可以在 UserControl 代码中定义新属性(并且已经这样做了,见下文),但是在按原样定义 UserControl 的情况下,控件 txtInput 的用户可以设置一些随机属性,比如在 xaml 中说 FontSize 没有我将 FontSize 定义为 UserControls 的属性。就像是:
<uc:LimitedInputUserControl x:Name="liucDescription" Title="Enter description:" InitialText="Enter text here" MaxLength="140" Grid.Row="1">
<txtInput FontSize=20/>
</uc:LimitedInputUserControl>
<UserControl x:Class="TestBed.UserControls.LimitedInputUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:TestBed"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid x:Name="grdGrid">
<Grid.Background>
<SolidColorBrush Opacity="0.5" Color="Orange" />
</Grid.Background>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Label x:Name="lblTitle" Content="{Binding Title}" />
<Label x:Name="lblLength" Grid.Column="1">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding ElementName=txtInput, Path=Text.Length}" />
<TextBlock Text="/" />
<TextBlock Text="{Binding MaxLength}" />
</StackPanel>
</Label>
<TextBox x:Name="txtInput" MaxLength="{Binding MaxLength}" Grid.Row="1" Grid.ColumnSpan="2" ScrollViewer.VerticalScrollBarVisibility="Auto" TextWrapping="Wrap" />
</Grid>
</UserControl>
代码如下:
namespace TestBed.UserControls
{
/// <summary>
/// Interaction logic for LimitedInputUserControl.xaml
/// </summary>
public partial class LimitedInputUserControl : UserControl
{
public LimitedInputUserControl()
{
InitializeComponent();
this.DataContext = this;
}
public string Title { get; set; }
private string sInitialText;
public string InitialText { get => sInitialText;
set
{
sInitialText = value;
txtInput.Text = value;
txtInput.SelectAll();
}
}
public int MaxLength { get; set; }
}
}
解决方案
推荐阅读
- c++ - 此代码失败,但为什么呢?返回整数指针的内存地址
- c# - 素数分解如何保证因子是素数?
- java - 读取文本文件的第一行并将其存储到数组列表中
- python-3.x - 在 macOS Catalina 中使用 pip install apache-airflow 安装气流时出错
- java - OutOfMemoryError:请求的数组大小超过了 apache camel 中的 VM 限制
- php - 如何使用 Laravel Envoy 运行 SSH 命令
- php - 为电子邮件地址创建动态重播
- python - 如何在多个熊猫列中将十六进制转换为整数
- css - 如何在 Create React App 应用程序中处理 3rd 方依赖项的 CSS
- matlab - Matlab.- 从每个元素都是时间表的单元格数组中删除重复项