J'ai le code suivant:
Code XAML:
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public static readonly DependencyProperty SectionTitleProperty =
DependencyProperty.Register(nameof(SectionTitle),
typeof(SectionTitle),
typeof(MainWindow));
public SectionTitle SectionTitle
{
get { return (SectionTitle)GetValue(SectionTitleProperty); }
set { SetValue(SectionTitleProperty, value); }
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
SectionTitle = SectionTitle.TitleBlock;
}
}
public enum SectionTitle
{
Normal,
TitleBlock
}
public class EnumConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var sectionType = (SectionTitle)value;
if (sectionType == SectionTitle.Normal)
return true;
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
Code C #
<Window x:Class="combobinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:combobinding"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Window.Resources>
<local:EnumConverter x:Key="isEnabledConverter" />
</Window.Resources>
<Grid>
<TextBox Text="Hello" IsEnabled="{Binding SectionTitle, Converter={StaticResource isEnabledConverter}}" />
</Grid>
</Window>
Je m'attendrais à ce que le EnumConverter soit appelé lorsque je règle le DependencyProperty SectionTitle et tout le point d'arrêt à l'intérieur de la méthode sera atteint.
Cependant, cela ne semble pas être le cas; et la propriété IsEnabled n'est pas liée à SectionTitle comme je le souhaite.
Quel est le problème avec ce code?
3 Réponses :
Le problème est le DataContext . La liaison ne trouve pas sa cible.
Vous pouvez définir le contexte dans la déclaration de la fenêtre. Ajoutez ceci à la balise Window dans votre XAML:
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Vous devez définir le DataContext de votre MainWindow. Vous pouvez facilement le faire dans le constructeur:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
...
Je pensais que DependencyProperty gère déjà INotifyPropertyChanged ?
Définissez la propriété Name sur votre Window avec Name = "MyWindow" , puis utilisez-la dans votre liaison comme ceci:
<TextBox Text="Hello" IsEnabled="{Binding ElementName=MyWindow, Path=SectionTitle, Converter={StaticResource isEnabledConverter}}" />