繁体   English   中英

WPF用户控件的公开属性

[英]Expose property for WPF user control

在这里,我在WPF中有一个用户控件,基本上是在一个窗格中显示文件夹树,而在另一个窗格(列表视图)中显示该目录中的文件。

现在,我公开了一个名为fileextensionfilter的属性,该属性基本上要求仅在列表视图中显示特定文件。 例如,如果fileextensionfilter = XML,则仅显示xml文件。

现在在我的主要应用程序中,我正在使用上述控制三次,但是具有不同的fileextensionfilet,例如1> xml仅另一个实例.pdf,依此类推。

现在我从settings.default.xmlfilter,settings.default.PDFFilter等获取扩展过滤器值......

这里的问题是当我未初始化usercontrol的加载控件属性,并且在构造函数中使用此属性并且在那个时候使用了某些东西(当时为“ null”),因此过滤器第一次不起作用。 下一步再次刷新它,将应用过滤器属性,因此它可以工作。

您可以尝试使用当前属性,并使用Loaded Event运行您在构造函数中当前正在运行的代码。 这是一个小例子:

MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525" xmlns:my="clr-namespace:WpfApplication1">
    <Grid>
        <my:UserControl1 FileExtensionFilter="RTF" HorizontalAlignment="Left" Margin="10,10,0,0" x:Name="userControl1" VerticalAlignment="Top" />
        <my:UserControl1 FileExtensionFilter="XML" HorizontalAlignment="Left" Margin="10,10,0,0" x:Name="userControl2" VerticalAlignment="Top" />
        <my:UserControl1 FileExtensionFilter="PDF" HorizontalAlignment="Left" Margin="10,10,0,0" x:Name="userControl3" VerticalAlignment="Top" />
    </Grid>
</Window>

用户控件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for UserControl1.xaml
    /// </summary>
    public partial class UserControl1 : UserControl
    {
        string filter = "NULL";
        public UserControl1()
        {
            InitializeComponent();
            System.Diagnostics.Debug.WriteLine("Property" + filter + "Set during Constructor");
        }

        public string FileExtensionFilter
        {
            get { return filter; }
            set { filter = value; }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Property" + filter + "Set during Loaded");
        }

        private void UserControl_Initialized(object sender, EventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Property" + filter + "Set during Initialized");
        }
    }
}

产量

在初始化期间设置PropertyNULLSet
PropertyNULLSet在构造期间
在初始化期间设置PropertyNULLSet
PropertyNULLSet在构造期间
在初始化期间设置PropertyNULLSet
PropertyNULLSet在构造期间
加载期间的PropertyRTFSet
加载期间的PropertyXMLSet
加载期间的PropertyPDFSet

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM