首页 > 解决方案 > 是否可以在没有代码的用户控件中设置子控件属性?

问题描述

我有一个从某个地方抓到的示例 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#wpfxamluser-controls

解决方案


推荐阅读