【问题标题】:Modify custom UserControl programmatically以编程方式修改自定义 UserControl
【发布时间】:2016-06-30 05:58:12
【问题描述】:

我已经制作了这个用户控件:

<UserControl
    x:Class="ScannerApp.Custom_Controls.LocationAndQuantity"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:ScannerApp.Custom_Controls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="20">
    <Grid Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Border x:Name="border" Background="{Binding Color}">
            <TextBlock x:Name="locationTxt" Text="{Binding Location}" HorizontalAlignment="Center"></TextBlock>
        </Border>
        <TextBlock x:Name="quantityTxt" Text="{Binding Quantity}" Grid.Column="1" HorizontalAlignment="Center" TextWrapping="Wrap" VerticalAlignment="Top"/>
    </Grid>
</UserControl>

我需要能够修改 TextBlocks 中的边框背景颜色和文本。但是,如果我创建一个新的自定义控件,无论如何我都无法设置它。

我试过了:

LocationAndQuantity customControl = new LocationAndQuantity(Color = "red", Location = "A-01-01", Quantity = "23");

或者这个:

LocationAndQuantity customControl = new LocationAndQuantity();
customContrl.border = ... //this just gives me error right away.

【问题讨论】:

    标签: c# wpf xaml user-controls


    【解决方案1】:

    您可以通过以下方式定义属性来绑定用户控件

    public partial class LocationAndQuantity : UserControl
    {
        public Brush Color { get; set; }
        public string  Location { get; set; }
        public int Quantity { get; set; }
    
        //The class must have default constructor
        public LocationAndQuantity()
        {
            this.InitializeComponent();
        }
    
        public LocationAndQuantity(string c,string l, int q)
        {
            this.Color = new SolidColorBrush((Color)ColorConverter.ConvertFromString(c));
            this.Location = l;
            this.Quantity = q;
            InitializeComponent();
            DataContext = this;            
        }
    }
    

    用途:

    LocationAndQuantity customControl = new LocationAndQuantity("red", "A-01-01", 10);
    //then add to stackpannel for example
    stackPanel.Children.Add(customControl);
    

    【讨论】:

    • 我刚刚创建了一个具有定义属性的类,并为创建的模型设置了 Datacontext,但这似乎更好。
    • 是的,逻辑也应该起作用。这也有效
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 2012-12-02
    • 1970-01-01
    • 2013-12-04
    • 2015-02-27
    • 2017-08-01
    • 1970-01-01
    相关资源
    最近更新 更多