UserControl background property Brush binding does not work - c#

Hello i am trying to initialize usercontrol with bacground which is binded in viewmodel. In model color is set but dependency property does not take it.
HeaderCropper xaml :
<UserControl x:Class="x.CustomControls.x"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:converters="clr-x.Converters"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="300"
Width="{Binding CropperWidth,ElementName=HeaderCropper}"
Height="{Binding CropperHeight,ElementName=HeaderCropper}"
x:Name="HeaderCropper">
<Thumb x:Name="CroppableArea" BorderThickness="1" Grid.Column="0" Grid.Row="0" Background='{Binding CropperColor}' BorderBrush="Black" Opacity="0.2"
HeaderCropper class :
public static DependencyProperty ColorProperty;
static HeaderCroper()
{
ColorProperty = DependencyProperty.Register("CropperColor",
typeof(Brush), typeof(HeaderCroper), new FrameworkPropertyMetadata(null));
}
public Brush CropperColor
{
get { return (Brush)GetValue(ColorProperty); }
set
{
SetValue(ColorProperty, value);
}
}
HeaderCropper binding :
<DataTemplate>
<custom:HeaderCroper Panel.ZIndex="1" Width="50" Height="50" CropperHeight="{Binding Height,Mode=TwoWay,NotifyOnTargetUpdated=True}"
CropperWidth="{Binding Width,Mode=TwoWay,NotifyOnTargetUpdated=True}"
MaxCropperHeight="{Binding ElementName=Image,Path=RenderSize.Height}"
MaxCropperWidth="{Binding ElementName=Image,Path=RenderSize.Width}"
InfoCommand="{Binding InfoCommand}"
InfoCommandParameter="{Binding Id}"
DeleteCropperCommand="{Binding DeleteCommand}"
DeleteCropperCommandParameter="{Binding Id}"
CropperLeft="{Binding CropperLeft,Mode=TwoWay,NotifyOnTargetUpdated=True}"
CropperTop="{Binding CropperTop,Mode=TwoWay,NotifyOnTargetUpdated=True}"
MainCanvas ="{Binding ElementName=CropperCanvas,NotifyOnTargetUpdated=True}"
Canvas.Left="0"
CropperColor="{Binding CropperColor,Mode=TwoWay,NotifyOnTargetUpdated=True}"
/>
</DataTemplate>
As you can see CropperColor parameter is passed but header cropper is ignoring it and not setting color. Any ideas?
UPDATE:
As I debug on private method key press I see that color is set but it is null while usercontroll is initializing.

Related

Data Binding to User Control Error Data.Binding cannot be converted to System.String

I'm new to WPF and I'm having trouble binding text to a user control I made. It's a simple control, it's just basically a button with text and a image that I want to reuse in several Views.
Here is my User Control's .cs
public partial class MenuItemUserControl : UserControl
{
public string TextToDisplay { get; set; }
public MenuItemUserControl()
{
InitializeComponent();
DataContext = this;
}
}
Here is my User Control's xaml
<UserControl x:Class="Class.Controls.MenuItemUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Class.Controls"
mc:Ignorable="d"
d:DesignHeight="83.33" d:DesignWidth="512">
<Grid>
<Button Style="{StaticResource MenuItemStyle}" Height="Auto" Width="Auto">
<DockPanel LastChildFill="True" Width="512" Height="83.33" HorizontalAlignment="Center" VerticalAlignment="Center">
<Image Source="/Resources/MenuArrow.png" Stretch="None" HorizontalAlignment="Left" VerticalAlignment="Center" DockPanel.Dock="Left"/>
<TextBlock d:Text="sample" Text="{Binding TextToDisplay, Mode=OneWay}" HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="{StaticResource MenuItems}"/>
</DockPanel>
</Button>
</Grid>
</UserControl>
Here is my View xaml
<Page x:Class="Class.Views.MenuOperate"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:uc="clr-namespace:Class.Controls"
xmlns:local="clr-namespace:Class.Views"
xmlns:properties="clr-namespace:Class.Properties"
xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls" xmlns:viewmodels="clr-namespace:Class.ViewModels" d:DataContext="{d:DesignInstance Type=viewmodels:MenuOperateViewModel}"
mc:Ignorable="d"
d:DesignHeight="500" d:DesignWidth="1024"
Title="MenuOperate">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="83.33"/>
<RowDefinition Height="83.33"/>
<RowDefinition Height="83.33"/>
<RowDefinition Height="83.33"/>
<RowDefinition Height="83.33"/>
<RowDefinition Height="83.33"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="512"/>
<ColumnDefinition Width="512"/>
</Grid.ColumnDefinitions>
<uc:MenuItemUserControl TextToDisplay="{Binding StartStop, Mode=TwoWay}" Grid.Row="0" Grid.Column="0"/>
</Grid>
</Page>
Here is my View Model .cs
namespace Class.ViewModels
{
public class MenuOperateViewModel : ObservableObject
{
private string? _StartStop;
public MenuOperateViewModel()
{
StartStop = Properties.Resources.MenuOperateStart;
}
public string? StartStop
{
get => _StartStop;
set => SetProperty(ref _StartStop, value);
}
}
}
This is the error I get in my View Xaml:
Object of Type 'System.Windows.Data.Binding' cannot be converted to type 'System.String'.
There are two things that prevent that the expression
TextToDisplay="{Binding StartStop}"
works.
The target property of the Binding, i.e. TextToDisplay must be a dependency property.
You must not explicity set the UserControl's DataContext. The Binding will resolve the source property path relative to the current DataContext, i.e. with DataContext = this; in the control's constructor, it expects the source property StartStop on the UserControl, which is obviously wrong.
For details, see Data binding overview
Your code should look like this:
public partial class MenuItemUserControl : UserControl
{
public static readonly DependencyProperty TextToDisplayProperty =
DependencyProperty.Register(
nameof(TextToDisplay),
typeof(string),
typeof(MenuItemUserControl));
public string TextToDisplay
{
get { return (string)GetValue(TextToDisplayProperty); }
set { SetValue(TextToDisplayProperty, value); }
}
public MenuItemUserControl()
{
InitializeComponent();
}
}
The Binding in the UserControl's XAML would then use a RelativeSource Binding.
<TextBlock Text="{Binding TextToDisplay,
RelativeSource={RelativeSource AncestorType=UserControl}}" />

Custom UserControl Template with Property-Binding

I created an custom UserControl which includes an Ellipse and a Label. The Label Content and the Color of the Ellipse is binded:
The Binding-Properties are DependencyProperties.
The color of the Ellipse is depended on the Status, which is a bool (a converter creates the Color)
This is the UserControl1.xaml:
<UserControl x:Class="Plugin_UPS.Views.UserControl1"
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:Converters="clr-namespace:WPF_Prism.Infrastructure.Converters.Ups;assembly=WPF_Prism.Infrastructure"
mc:Ignorable="d"
x:Name="UC1"
d:DesignWidth="200" Height="40">
<UserControl.Resources>
<ResourceDictionary>
<Converters:BoolToColorConverter x:Key="BoolToColorConverter"/>
</ResourceDictionary>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Height="42" Width="504">
<StackPanel HorizontalAlignment="Left" Margin="0,0,0,0" Height="Auto" Width="Auto" Grid.Column="0" Grid.Row="0">
<Grid Height="Auto" Width="Auto" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="0,0,0,0"
MinWidth="200" MaxWidth="200" MinHeight="35" MaxHeight="40">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Ellipse HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Column="0" Grid.Row="0"
Fill="{Binding Status, Converter={StaticResource BoolToColorConverter}, UpdateSourceTrigger=PropertyChanged}"
Height="15"
Width="15"
StrokeThickness="1"
Stroke="Black">
</Ellipse>
<Label Content="{Binding Text}" Height="Auto" Width="Auto" Margin="0,0,0,0" HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="16" Grid.Column="1" Grid.Row="0" />
</Grid>
</StackPanel>
</Grid>
</UserControl>
This is the UserControl1.xaml.cs:
namespace Plugin_UPS.Views
{
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(UserControl1));
public bool Status
{
get { return (bool)GetValue(StatusProperty); }
set { SetValue(StatusProperty, value); }
}
public static readonly DependencyProperty StatusProperty =
DependencyProperty.Register("Status", typeof(bool), typeof(UserControl1));
}
}
This is my UPSViewModel.cs:
namespace Plugin_UPS.ViewModel
{
public class UPSViewModel
{
public UPSViewModel()
{
}
public string UpsModelText { get { return "Model"; } }
private bool replaceBatteryCondition;
public bool ReplaceBatteryCondition { get { return replaceBatteryCondition; } set { replaceBatteryCondition = value; } }
}
}
This is my UPSView.xaml:
(here I implement the UserControl1)
<UserControl x:Class="Plugin_UPS.Views.UPSView"
x:Name="UPSUC"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
xmlns:local="clr-namespace:Plugin_UPS"
xmlns:Controls="clr-namespace:WPF_Prism.Controls.Controls;assembly=WPF_Prism.Controls"
xmlns:ViewModel="clr-namespace:Plugin_UPS.ViewModel"
xmlns:Views="clr-namespace:Plugin_UPS.Views"
d:DataContext="{d:DesignInstance ViewModel:UPSViewModel}"
mc:Ignorable="d"
d:DesignHeight="840" d:DesignWidth="1260">
<Grid>
<StackPanel>
<Views:UserControl1 Margin="10,20,10,10" DataContext="{Binding RelativeSource={RelativeSource Self}}" Text="{Binding UpsModelText}" Status="{Binding ReplaceBatteryCondition}"></Views:UserControl1>
</StackPanel>
</Grid>
</UserControl>
But the binding for "Status" and "Text" is not working.
(Status="True" or Text="Model" is working).
Do you have any ideas what the problem could be?
Is there a problem with the DataContext?
best regards
Phil
You must not set the UserControl's DataContext to itself, as done by
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Remove that assignment and write
<Views:UserControl1 Margin="10,20,10,10"
Text="{Binding UpsModelText}"
Status="{Binding ReplaceBatteryCondition}" />
Now you'll have to specify the source of the bindings in the UserControl's XAML.
There are multiple ways to do that, one of them is to set the RelativeSource property like this:
<Label Content="{Binding Text,
RelativeSource={RelativeSource AncestorType=UserControl}}" ... />
<Ellipse Fill="{Binding Status,
RelativeSource={RelativeSource AncestorType=UserControl},
Converter={StaticResource BoolToColorConverter}}" ... />
Note that setting UpdateSourceTrigger=PropertyChanged on the Fill Binding doesn't make sense.

Custom Button with Binding

I would like to create a Custon Button in WPF, so I have write this code:
<UserControl x:Class="RiabilitazioneCognitiva.ButtonPersonalizzati"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" Width="Auto" Height="Auto">
<FrameworkElement.Resources>
<ResourceDictionary Source="GlassButton.xaml" />
</FrameworkElement.Resources>
<Button x:Name="pippo" Style="{DynamicResource GlassButton}"
Click="button_Click">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Text}" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="#FFFFFFFF" />
</StackPanel>
</Button>
</UserControl>
Now i insert this Button in my page, so i try this code:
<Window xmlns:RiabilitazioneCognitiva="clr-namespace:RiabilitazioneCognitiva" x:Name="framePrincipale" x:Class="RiabilitazioneCognitiva.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:RiabilitazioneCognitiva"
Title="Stop"
Height="{Binding}"
Width="{Binding}"
Background="White"
WindowStartupLocation="CenterScreen"
WindowStyle="None"
WindowState="Maximized"
ResizeMode="NoResize">
</Window>
<Grid>
<local:ButtonPersonalizzati />
</Grid>
It found, but if i insert this i don't see Button
<local:ButtonPersonalizzati x:Text="pp" >
Can we help me?
Thanks
PS: in ButtonPersonalizzati.cs i have this
public string Text {
get{return Text;}
}
You haven't set your data context. There are a variety of ways to deal with this, but my typical approach is to do something like this:
<UserControl ...
x:Name="ucThis">
...
<TextBlock Text="{Binding ElementName=ucThis Path=Text}" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="#FFFFFFFF" />
...
</UserControl>
Close the tag local:ButtonPersonalizzati
<local:ButtonPersonalizzati x:Name="pp" local:Text="Pippo" />
Define Text as a DependencyProperty so you can bind to it:
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(ButtonPersonalizzati), new UIPropertyMetadata(""));
You should also set the DataContext in the constructor of your class:
this.DataContext=this;

User control's dependency property not binding

I have user control with dependency property. When I try bind it in windows it doesn't work. But when I change binding to normal parameter (in this situation, true) it's working. What i need to do to make my binding working? Maybe something with DataContext? Here is my code:
First user control's xaml:
<UserControl x:Class="DPTest.CustomUserControl"
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"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
d:DesignHeight="100" d:DesignWidth="200"
DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}">
<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}">
<TextBlock Text="{Binding Property}"/>
</Grid>
</UserControl>
Code behind:
public partial class CustomUserControl : UserControl, INotifyPropertyChanged
{
public static readonly DependencyProperty DPTestProperty = DependencyProperty.Register("DPTest", typeof(bool), typeof(CustomUserControl), new PropertyMetadata(default(bool), propertyChangedCallback));
public bool DPTest
{
get
{
return (bool)GetValue(DPTestProperty);
}
set
{
SetValue(DPTestProperty, value);
}
}
private bool _property;
public bool Property
{
get
{
return _property;
}
set
{
_property = value;
RaisePropertyChanged("Property");
}
}
private static void propertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = d as CustomUserControl;
control.Property = (bool)e.NewValue;
}
public CustomUserControl()
{
InitializeComponent();
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
In the windows where i put this user control data context is set to my view model:
<phone:PhoneApplicationPage
x:Class="DPTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:my="clr-namespace:DPTest"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True"
DataContext="{Binding Main, Source={StaticResource Locator}}">
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
<TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<my:CustomUserControl Name="cstom" DPTest="{Binding Property}"/>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
In the view model I have property which is binded to DPTest.
public class MainViewModel : ViewModelBase
{
private bool _property;
public bool Property
{
get { return _property; }
set
{
_property = value;
RaisePropertyChanged("Property");
}
}
public MainViewModel()
{
Property = true;
}
}
When I run this application Textblock have value False but this should be True and propertyChangedCallback isn't even called. What i need to do?
Thanks
Try this:
<UserControl x:Class="DPTest.CustomUserControl"
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" mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}" FontSize="{StaticResource
PhoneFontSizeNormal}" Foreground="{StaticResource PhoneForegroundBrush}" d:DesignHeight="100"
d:DesignWidth="200"
x:Name="self">
<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}">
<TextBlock Text="{Binding Property, ElementName=self}"/>
</Grid>
You have bind UserControl DataContext to itself since you want to bind Property present in CustomUserControl to TextBlock inside it which is completely fine.
But when you use CustomUserControl in Window, it won't inherit Window's DataContext since its explicitly set on UserControl declaration. So, binding engine is trying to look for property in UserControl which it can't fine.
Note: Binding engine looks for property inside it's DataContext otherwise instructed to look somewhere else using RelativeSource, ElementName, x:Reference etc.
So you need to manually provide binding engine the property instance like this:
<my:CustomUserControl Name="cstom"
DPTest="{Binding Path=DataContext.Property,
ElementName=LayoutRoot}"/>
Explanation for working with DPTest="True":
Since you already manually provided the value to DP, binding engine doesn't have to worry about finding it in DataContext.

Visibility Binding using DependencyProperty

I've some simple code below that uses a ToggleButton.IsChecked property to set the Visibility of a TextBlock. It works fine. Since this doesn't quite fit in with my program's structure, I'm trying to bind the visibility of another TextBlock to a DependencyProperty of "this". It compiles fine, but it produces no effect. I'm doing something wrong, just not sure what.
XAML
<Window x:Class="ToggleButtonTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Width="200" Height="100">
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</Window.Resources>
<StackPanel>
<ToggleButton x:Name="toggleButton" Content="Toggle"
IsChecked="True" Checked="toggleButton_Checked"/>
<TextBlock Text="Some Text"
Visibility="{Binding IsChecked,
ElementName=toggleButton,
Converter={StaticResource BooleanToVisibilityConverter}}"/>
<TextBlock Text="More Text"
Visibility="{Binding ShowMoreText,
ElementName=this,
Converter={StaticResource BooleanToVisibilityConverter}}"/>
</StackPanel>
</Window>
C#
using System.Windows;
namespace ToggleButtonTest
{
public partial class MainWindow : Window
{
static MainWindow()
{
FrameworkPropertyMetadata meta =
new FrameworkPropertyMetadata(true,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault);
ShowMoreTextProperty =
DependencyProperty.Register("ShowMoreText",
typeof(bool), typeof(MainWindow), meta);
}
public MainWindow()
{
InitializeComponent();
}
public static readonly DependencyProperty ShowMoreTextProperty;
public bool ShowMoreText
{
get
{
return (bool)GetValue(ShowMoreTextProperty);
}
set
{
SetValue(ShowMoreTextProperty, value);
}
}
private void toggleButton_Checked(object sender, RoutedEventArgs e)
{
ShowMoreText = toggleButton.IsChecked.Value;
}
}
}
Edit:
Having had this answered, I want to post my working code...
XAML
<Window x:Class="ToggleButtonTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Width="200" Height="100"
Name="thisWindow">
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</Window.Resources>
<StackPanel>
<ToggleButton x:Name="toggleButton"
Content="Toggle"
IsChecked="{Binding Path=ShowMoreText, ElementName=thisWindow}"/>
<TextBlock Text="More Text"
Visibility="{Binding Path=ShowMoreText,
ElementName=thisWindow,
Converter={StaticResource BooleanToVisibilityConverter}}"/>
</StackPanel>
</Window>
C#
using System.Windows;
namespace ToggleButtonTest
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public static readonly DependencyProperty ShowMoreTextProperty =
DependencyProperty.Register("ShowMoreText", typeof(bool),
typeof(MainWindow), new FrameworkPropertyMetadata(true,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public bool ShowMoreText
{
get
{
return (bool)GetValue(ShowMoreTextProperty);
}
set
{
SetValue(ShowMoreTextProperty, value);
}
}
}
}
ElementName must really be an element name. this doesn't fly. Fortunately, you do have an element of type MainWindow here with a ShowMoreText property: the root Window element.
Give the Window a name and use that as ElementName, as below:
<Window x:Class="ToggleButtonTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Width="200" Height="100"
x:Name="thisWindow">
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</Window.Resources>
<StackPanel>
<ToggleButton x:Name="toggleButton" Content="Toggle"
IsChecked="True" Checked="toggleButton_Checked"/>
<TextBlock Text="Some Text"
Visibility="{Binding IsChecked,
ElementName=toggleButton,
Converter={StaticResource BooleanToVisibilityConverter}}"/>
<TextBlock Text="More Text"
Visibility="{Binding ShowMoreText,
ElementName=thisWindow,
Converter={StaticResource BooleanToVisibilityConverter}}"/>
</StackPanel>
</Window>
Note that you can do the same using RelativeSource Self, but I prefer the method above.
The way you have it set up currently won't ever set ShowMoreText to false. The Checked handler will only be called when the ToggleButton's IsChecked changes from false to true. To also go the other way you need a handler for Unchecked as well. The best way to handle this situation would be to instead set a Binding on the ToggleButton that will do both without any event handlers (using Jay's changes):
IsChecked="{Binding Path=ShowMoreText, ElementName=thisWindow}"
Give your Window a name and set the ElementName to that name, instead of using "this".

Categories

Resources