WPF Tips: Binding Window Title

想让Window的标题显示正在操作的文件名。

 

xaml:

 

<Window x:Class="PSSv25.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
Title="{Binding Path=FileName, StringFormat={}{0} - PSSv25}" Height="485" Width="667">

 

cs:

public string FileName
{
get { return (string)GetValue(FileNameProperty); }
set { SetValue(FileNameProperty, value); }
}
public static readonly DependencyProperty FileNameProperty = 
DependencyProperty.Register("FileName",
typeof(string),typeof(MainWindow),new UIPropertyMetadata(null));

public MainWindow()
{
InitializeComponent();
FileName = "Untitled.txt"; 
}

 

或:

public string FileName
{
get;
set;
}
public MainWindow()
{
InitializeComponent();
DataContext = this;
FileName = "Untitled.txt"; 
}

 

更新:

由于几个子窗口中也需要显示文件名称,如果每个window都要上面一段代码,而且如果filename有变动会比较麻烦。所以又将FileName放在了一个类里:

Executor.cs:

public class Executor : DependencyObject
    {
        public static readonly DependencyProperty FileNameProperty =
        DependencyProperty.Register("FileName", typeof(string),
        typeof(Executor), new UIPropertyMetadata(null));
        public string FileName
        {
            get { return (string)GetValue(FileNameProperty); }
            set { SetValue(FileNameProperty, value); }
        }

        public static Executor Instance { get; private set; }

        static Executor()
        {
            Instance = new Executor();
        }

        public static void Init()
        {            
            Instance.FileName = "Untitled.txt";
        }  
...
}  

  

 

MainWindow.xaml:

<Window x:Class="PatentSequenceStandardv25.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        
        xmlns:local="clr-namespace:PSSv25"
    Title="{Binding Source={x:Static local:Executor.Instance}, Path=FileName, StringFormat={}{0} - PSSv25}" Height="485" Width="667">

MainWindow.cs

public MainWindow()
        {
            InitializeComponent();            
            Initialize();           
        }

private void Initialize()
        {
            try
            {                
                Logger.InitLogFile();
                Executor.Initialize();               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }            
        }

其他窗口xaml:

<Window x:Class="PSSv25.Window_PD"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        
        xmlns:local="clr-namespace:PSSv25"
        Title="{Binding Path=FileName, StringFormat=PD - {0}, Source={x:Static local:Executor.Instance}}" 
        Height="370" Width="630"
        ResizeMode="NoResize">

 

posted @ 2016-03-18 11:11  Jane&Coding  阅读(1040)  评论(0)    收藏  举报