(WPF) Привязка не показывает ничего в пользовательском интерфейсе - PullRequest
0 голосов
/ 15 февраля 2020

В настоящее время я изучаю WPF и пытаюсь проверить некоторую привязку. Здесь я хочу связать заголовок моей вкладки со свойством fileName в MainWindow.xaml.cs, но он ничего не показывает

Я не вижу ошибок в окне вывода либо DataContext в теге Window:

DataContext="{Binding RelativeSource={RelativeSource Self}}"

Связывание в xaml:

<TabItem Header="{Binding fileName, Mode=TwoWay}" x:Name="Header_Tab" Height="20" Width="175">

Моя собственность:

protected void NotifyPropertyChanged(string PropertyName)
        {
            if (PropertyChanged != null)

                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(PropertyName));

        }
...
public string filePath { get; set; }
        public string folderPath { get; set; }
        public string fileName
        {
            get
            {
                return Path.GetFileName(filePath);
            }
            set
            {
                if (value != Path.GetFileName(filePath))
                {
                    value = Path.GetFileName(filePath);
                    NotifyPropertyChanged(fileName);
                }
            }
        }

1 Ответ

0 голосов
/ 15 февраля 2020

Свойство filePath должно быть реализовано так:

private string _filePath;
public string filePath 
{ 
    get
    {
        return _filePath;
    }  
    set
    {
        if(value != _filePath)
        {
            _filePath = value;
            NotifyPropertyChanged("filePath");

            // Notify the UI that it should update fileName 
            // when there is a change on filePath
            NotifyPropertyChanged("fileName");
        }
    }
}

И свойство fileName должно быть доступно только для чтения:

public string fileName
{
    get
    {
        return Path.GetFileName(_filePath);
    }
}
...