公开WPF用户控件的属性

时间:2012-11-23 03:42:49

标签: c# wpf user-controls wpf-controls

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

现在我公开了一个名为fileextensionfilter的属性,它基本上只需要在listview中显示特定文件。例如如果fileextensionfilter = XML,它只显示xml文件。

现在在我的主应用程序中我使用上面的控制三次,但是使用了差异文件扩展文件,例如1> xml另一个实例.pdf等等......

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

这里的问题是当我加载控件的usercontrol属性没有被初始化时,我在构造函数中有一些东西使用这个属性和(当时“null”)所以过滤器不能在第一次工作。接下来它再次刷新过滤器属性将被应用,因此它可以工作。

1 个答案:

答案 0 :(得分:1)

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

<强> 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