Custom Button with Binding - c#

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;

Related

UserControl background property Brush binding does not work

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.

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.

How to use binding in a TabItem with DataTemplate in WPF?

I'm trying to do something basic (I think!), but I've got a problem. I have got a TabControl and 3 TabItems. The 2 first items must be untouched, and I want to apply a dataTemplate on the third tabItem, so I used a DataTemplateSelector. This is OK, it works. But then, I want to fill data in the third tabItem with my datamodel. Binding is not working because my DataContext is always "null" in the tabItem. How can I set the DataContext in the tabItem created by the dataTemplate ? Here is my code :
XAML :
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="910" Width="1200">
<Window.Resources>
<DataTemplate x:Key="configurationTemplate" DataType="{x:Type local:ConfigurationDatamodel}">
<local:ConfigurationTemplateUC DataContext="{Binding DataContext.ConfigurationDatamodel}" />
</DataTemplate>
<local:TabItemTemplateSelector ConfigurationTemplate="{StaticResource configurationTemplate}" x:Key="tabItemTemplateSelector"/>
</Window.Resources>
<Grid>
<TabControl Height="800" HorizontalAlignment="Stretch" Margin="0,0,0,0" Name="tabControl1" VerticalAlignment="Top" ContentTemplateSelector="{StaticResource tabItemTemplateSelector}">
<TabItem Header="TabItem1" Name="tabItem1" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<some stuff />
</TabItem>
<TabItem Header="TabItem2" Name="tabItem2" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<some stuff />
</TabItem>
<TabItem Header="TabItem3" Name="tabItem3" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
</TabItem>
</TabControl>
</Grid>
</Window>
UserControl of my DataTemplate :
<UserControl x:Class="WpfApplication1.ConfigurationTemplateUC"
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"
d:DesignHeight="800" d:DesignWidth="1000">
<Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<Label Content="File name : " Height="28" HorizontalAlignment="Left" Margin="50,43,0,0" Name="label1" VerticalAlignment="Top" FontSize="16"/>
<Label Content="{Binding Path=File}" FontSize="16" Height="28" HorizontalAlignment="Left" Margin="160,43,0,0" Name="label2" VerticalAlignment="Top" Width="324" />
</Grid>
</UserControl>
Datamodel :
public class ConfigurationDatamodel
{
private string file;
public string File
{
get { return this.file; }
set
{
this.file= value;
}
}
public ConfigurationDatamodel()
{}
public ConfigurationDatamodel(string file)
{
this.file= file;
}
}
Code-behind :
public MainWindow()
{
ConfigurationDatamodel dt1 = new ConfigurationDatamodel("example.txt");
InitializeComponent();
tabItem3.DataContext = dt1;
}
There is no binding errors in the console, but the label containing the filename is always empty. The DataContext of the UserControl "ConfigurationTemplateUC" is always "null".
Any thoughts?
EDIT
If I set the DataContext in the contructor of the UserControl, it works :
public ConfigurationTemplateUC()
{
InitializeComponent();
ConfigurationDatamodel dt1 = new ConfigurationDatamodel("example.txt");
this.DataContext = dt1;
}
How can I set this dataContext with the DataTemplate ?
In your DataTemplate, Remove the DataContext binding from
<local:ConfigurationTemplateUC DataContext="{Binding DataContext.ConfigurationDatamodel}" />
...leaving only
<local:ConfigurationTemplateUC />
UI in a DataTemplate automatically gets the bound data as its DataContext, so in your case you override the correct DataTemplate with a path to something that can't be found.
EDIT:
Also, you don't need a DataTemplateSelector to do this. You can remove the selector and instead simply use TabItem.ContentTemplate:
<TabItem Header="TabItem3" Name="tabItem3" ContentTemplate="{StaticResource configurationTemplate}" >
...

WPF ListBox bind ItemsSource with MVVM-light

XAML
<Window x:Class="Html5Mapper.Mapper.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wpt="http://schemas.xceed.com/wpf/xaml/toolkit"
Title="HTML mapper" Height="300" Width="600" >
<Window.DataContext>
<Binding Path="Main" Source="{StaticResource Locator}"/>
</Window.DataContext>
<ListBox Name="lbFiles" ItemsSource="{Binding Filescollection, Mode=OneWay}" Width="240" Height="220">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Margin="0,2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<Image Source="HTML.png" Height="40" Width="32" />
<TextBlock Grid.Column="1" Text="{Binding Name}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
MainViewModel.cs
public ObservableCollection<Files> Filescollection { get; set; }
public MainViewModel()
{
this.Filescollection = new ObservableCollection<Files>();
SelectFilesAction();
}
private void SelectFilesAction()
{
this.Filescollection.Add(new Files { Name = "index.html", Path = "C:\\Files"});
//lbFiles.ItemsSource = docs;
}
Q: What else do I need to get the docs object into the Listbox ?
In my opinion you are binding your controls to wrong datacontect, check output window for erros. You might want to set datacontext of main window to your MainViewModel (in codebehind or similar). Also why do you create another instance for docs? It is useless.
public ObservableCollection<Files> Filescollection {get;set;}
public MainViewModel()
{
this.Filescollection = new ObservableCollection<Files>();
SelectFilesAction();
}
private void SelectFilesAction()
{
Filescollection.Add(new Files { Name = "index.html", Path = "C:\\Files"});
}
Vidas is correct in that the DataContext of your Window is wrong, it needs to be your MainViewModel class.
Get rid of this:
<Window.DataContext>
<Binding Path="Main" Source="{StaticResource Locator}"/>
</Window.DataContext>
And add this to the Window tag:
<Window DataContext="{StaticResource MainViewModel}">
And that should do it.
<UserControl x:Class="RetailPOS.View.Usercontrols.MainWindow.Products"
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"
mc:Ignorable="d"
xmlns:ctrl="clr-namespace:RetailPOS.View.Usercontrols.MainWindow"
d:DesignHeight="200" d:DesignWidth="490" **DataContext="{Binding Source={StaticResource Locator}, Path=CategoryVM}"**
xmlns:my="clr-namespace:WpfLab.Controls;assembly=WpfLab.Controls">
<UserControl.Resources>
</UserControl.Resources>
<Grid Width="490" Height="360">
<ListBox Name="LstProduct" ItemsSource="{Binding LstProduct}" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal" Margin="0" Height="Auto" Width="490" >
</WrapPanel>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Button Margin="1" Content="{Binding Name}" Height="53" Background="{Binding Color}" HorizontalAlignment="Right" Width="79"
Command="{Binding DataContext.ShowProductCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}"
CommandParameter="{Binding}">
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>
In the code behind
private ObservableCollection<ProductDTO> _lstProduct;
public ObservableCollection<ProductDTO> LstProduct
{
get { return _lstProduct; }
set
{
_lstProduct = value;
RaisePropertyChanged("LstProduct");
}
}
/// <summary>
/// Get all Commonly Used Products
/// </summary>
/// <returns>returns list of all Commonly Used products present in database</returns>
private void FillCommonProducts()
{
LstProduct = new ObservableCollection<ProductDTO>(from item in ServiceFactory.ServiceClient.GetCommonProduct()
select item);
}

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