I have a border in WPF that I am trying to enable or disable based on two properties in the viewmodel: ConnectedVisibility and OperatingMode. This data trigger disables the border when connectedvisibility visibility is not set to "Visible". But it does not work for OperatingMode. For OperatingMode other than 0, the border should be disabled but it stays enabled. It appears that there is no impact of OperatingMode changing its value at all. Even the breakpoints that I put in the convertor are not being hit except when the program first starts up. The bindings look Ok as there is no problem shown in Debug output for these bindings. Any help is appreciated.
The Style is
<Style x:Key="EnableOnConnectBorderCorrected" TargetType="{x:Type Border}">
<!--<Setter Property="BorderBrush" Value="#FFDADADA"/>-->
<Setter Property="BorderBrush" Value="Red"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="CornerRadius" Value="2"/>
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding ConnectedVisibility}" Value="Visible"/>
<Condition Binding="{Binding OperatingMode}" Value="0"/>
</MultiDataTrigger.Conditions>
<Setter Property="IsEnabled" Value="True"/>
</MultiDataTrigger>
<DataTrigger Binding="{Binding OperatingMode, Converter={x:Static VM:IsEqualOrGreaterThanSHORTConverter.Instance}, ConverterParameter=1,Mode=TwoWay}" Value="True">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
<DataTrigger Binding="{Binding ConnectedVisibility}" Value="Collapsed">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
The convertor used in the style is ->
public class IsEqualOrGreaterThanSHORTConverter : IValueConverter
{
public static readonly IValueConverter Instance = new IsEqualOrGreaterThanSHORTConverter();
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
short iValue = (short)value;
short compareToValue = System.Convert.ToInt16(parameter);
return iValue >= compareToValue;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
The XAML where this style is applied is
<Border Name="RebootDash" Grid.Row="2" Grid.Column="1" Style="{StaticResource EnableOnConnectBorderCorrected}" BorderBrush="#FFDADADA" BorderThickness="1" CornerRadius="2" Width="Auto" Margin="0,1,1,0">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Border Grid.Row="2" Background="Wheat"/>
<telerik:RadButton Command="{Binding ResetUnitCommand, Source={StaticResource UnitCommandProvider}}" Style="{StaticResource DashBoardImageButton}">
<Image Grid.Row="0" Source="/Images/UnitManagementImages/IMG_THOR_UNITResetUnit128.png"
ToolTip="{x:Static properties:Resources.Unit_Command_ResetUnit}"
Width="40" Height="40"
Margin="0,5,0,5"
HorizontalAlignment="Center"/>
</telerik:RadButton>
<TextBlock Grid.Row="2" Text="{x:Static properties:Resources.Unit_Command_ResetUnit}" HorizontalAlignment="Center" Margin="5,5,5,5"/>
</Grid>
</Border>
The properties to which it is bound are
public Visibility ConnectedVisibility
{
get { return connectedVisibility; }
set
{
if (connectedVisibility == value) return;
connectedVisibility = value;
RaisePropertyChanged("ConnectedVisibility");
}
}
public short OperatingMode
{
get { return UnitOperatingModeVM.OperatingMode; }
set
{
UnitOperatingModeVM.OperatingMode = value;
}
}
since you have only one condition to enable the same, so perhaps setting IsEnabled to False by default should do the trick
<Style x:Key="EnableOnConnectBorderCorrected" TargetType="{x:Type Border}">
<!--<Setter Property="BorderBrush" Value="#FFDADADA"/>-->
<Setter Property="BorderBrush" Value="Red"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="CornerRadius" Value="2"/>
<Setter Property="IsEnabled" Value="False"/>
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding ConnectedVisibility}" Value="Visible"/>
<Condition Binding="{Binding OperatingMode}" Value="0"/>
</MultiDataTrigger.Conditions>
<Setter Property="IsEnabled" Value="True"/>
</MultiDataTrigger>
</Style.Triggers>
</Style>
I have added <Setter Property="IsEnabled" Value="False"/> in the style which will by default disable the control and I have removed the other redundant conditions
so as result when the both conditions in MultiDataTrigger will meet it will enable the same, otherwise it remains disabled
above example assumes that both of the property in MultiDataTrigger ConnectedVisibility & OperatingMode are notifying the changes.
you may also need to add the notification for OperatingMode in order for MultiDataTrigger to fire the trigger
public short OperatingMode
{
get { return UnitOperatingModeVM.OperatingMode; }
set
{
UnitOperatingModeVM.OperatingMode = value;
RaisePropertyChanged("OperatingMode");
}
}
Is your OperatingMode property set implementation call RaisePropertyChanged("OperatingMode");
private short operatingMode;
public short OperatingMode
{
get
{
return operatingMode;
}
set
{
if (operatingMode != value)
{
operatingMode = value;
this.RaisePropertyChanged("OperatingMode");
}
}
}
Related
I have a customized ComboBox to handle the text input and filter the itemsource. The problem I'm having is when I open the ComboBox the textBox is focused and let me write in it, then if I close and open it again, the TextBox is not focused and I cant write anything inside. I've discovered that the first time the comboBox is opening it is setting the focus on the TextBox but when I close it the TextBox keeps its IsFocused property true so when reopening the problem happens. It's just when opening and reopening clicking the comboBox because if I click outside the ComboBox to close it and then open it again everything works nice.
Here is the customized style I wrote and the ComboBox I'm using.
<Style x:Key="FilteringComboBox" TargetType="ComboBox">
<Setter Property="SnapsToDevicePixels" Value="true" />
<Setter Property="OverridesDefaultStyle" Value="true" />
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto" />
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Visible" />
<Setter Property="ScrollViewer.CanContentScroll" Value="true" />
<Setter Property="IsEditable" Value="True"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="FontFamily" Value="Coves"/>
<Setter Property="FontWeight" Value="Normal"/>
<Setter Property="FontSize" Value="12"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ComboBox">
<Border x:Name="TopBorder"
CornerRadius="8"
BorderBrush="Grey"
BorderThickness="1"
Padding="10,0,1,0">
<Border.Background>
<LinearGradientBrush EndPoint="0.504,1.5" StartPoint="0.504,0.03">
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="#e3e3e5" Offset="0.65"/>
</LinearGradientBrush>
</Border.Background>
<Grid>
<ToggleButton
Name="ToggleButton"
Template="{DynamicResource FilteringComboBoxToggleButton}"
Grid.Column="2"
Focusable="false"
IsChecked="{Binding Path=IsDropDownOpen,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}"
ClickMode="Press">
</ToggleButton>
<TextBlock Name="ContentSite" IsHitTestVisible="False"
Text="{Binding Source={StaticResource Proxy}, Path=Data.Name, UpdateSourceTrigger=PropertyChanged}"
Visibility="Visible" Foreground="#37465c"
Padding="3,3,23,3" VerticalAlignment="Center"
HorizontalAlignment="Left" />
<TextBox x:Name="PART_EditableTextBox" MaxWidth="215" MinWidth="100"
Text="{Binding Source={StaticResource Proxy}, Path=Data.FilterText, UpdateSourceTrigger=PropertyChanged}"
Foreground="#37465c"
HorizontalAlignment="Left" VerticalAlignment="Center" Margin="3,3,23,3" Focusable="True" Background="Transparent"
Visibility="Collapsed"/>
<Popup x:Name="Popup" Placement="Bottom" IsOpen="{TemplateBinding IsDropDownOpen}" AllowsTransparency="True"
Focusable="False" PopupAnimation="Fade">
<StackPanel Orientation="Vertical" Width="215">
<Grid Name="DropDown" SnapsToDevicePixels="True"
MaxHeight="{TemplateBinding MaxDropDownHeight}">
<Border x:Name="DropDownBorder" BorderThickness="1"
BorderBrush="#888">
<Border.Background>
<LinearGradientBrush EndPoint="0.504,1.5" StartPoint="0.504,0.03">
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="#e3e3e5" Offset="0.65"/>
</LinearGradientBrush>
</Border.Background>
<ScrollViewer Margin="0" SnapsToDevicePixels="True">
<StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained"/>
</ScrollViewer>
</Border>
</Grid>
</StackPanel>
</Popup>
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Cursor" Value="Hand"/>
</Trigger>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="IsDropDownOpen" Value="True"/>
<Setter TargetName="PART_EditableTextBox" Property="Visibility" Value="Visible" />
<Setter TargetName="ContentSite" Property="Visibility" Value="Collapsed" />
<Setter Property="IsEditable" Value="True"/>
</Trigger>
<Trigger Property="IsMouseCaptured" Value="False">
<Setter Property="IsDropDownOpen" Value="False"/>
<Setter TargetName="PART_EditableTextBox" Property="Visibility" Value="Collapsed" />
<Setter TargetName="ContentSite" Property="Visibility" Value="Visible" />
<Setter Property="Text" Value=""/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I tried adding this event handler to remove the focus but it isn't working
private static void QuantityBox_IsMouseCapturedWithin(object sender, DependencyPropertyChangedEventArgs e)
{
var qBox = sender as ComboBox;
if (qBox.IsDropDownOpen == false)
{
Keyboard.ClearFocus();
flag = true;
}
}
Hope that this helps someone, the erratic behaviour was happening because I was using these triggers:
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="IsDropDownOpen" Value="True"/>
<Setter TargetName="PART_EditableTextBox" Property="Visibility" Value="Visible" />
<Setter TargetName="ContentSite" Property="Visibility" Value="Collapsed" />
<Setter Property="IsEditable" Value="True"/>
</Trigger>
<Trigger Property="IsMouseCaptured" Value="False">
<Setter Property="IsDropDownOpen" Value="False"/>
<Setter TargetName="PART_EditableTextBox" Property="Visibility" Value="Collapsed" />
<Setter TargetName="ContentSite" Property="Visibility" Value="Visible" />
<Setter Property="Text" Value=""/>
</Trigger>
The triggers were ment to handle the visibility toggle between the TexBlock and the TextBox (showing the TextBlock when the ComboBox was inactive and the TextBox when it is focused so the user can type and filter).
So I removed the triggers and handled that behaviour in a dependency property:
public static readonly DependencyProperty MouseCapturedProperty = DependencyProperty.RegisterAttached("MouseCaptured",
typeof(bool), typeof(QuantitiesBoxBehaviours),
new UIPropertyMetadata(false, MouseCapturedPropertyChangedCallback));
public static bool GetMouseCaptured(UIElement element)
{
return (bool)element.GetValue(MouseCapturedProperty);
}
public static void SetMouseCaptured(UIElement element, bool command)
{
element.SetValue(MouseCapturedProperty, command);
}
private static void MouseCapturedPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var qBox = d as ComboBox;
bool value = GetMouseCaptured(qBox);
if (qBox != null && value)
{
qBox.IsMouseCaptureWithinChanged += QBox_IsMouseCaptureWithinChanged;
qBox.DropDownOpened += QBox_DropDownOpened;
}
}
private static void QBox_DropDownOpened(object sender, EventArgs e)
{
var qBox = sender as ComboBox;
var template = qBox.Template;
var txtBox = template.FindName("PART_EditableTextBox", qBox) as TextBox;
var txtBlock = template.FindName("ContentSite", qBox) as TextBlock;
txtBlock.Visibility = Visibility.Collapsed;
txtBox.Visibility = Visibility.Visible;
}
private static void QBox_IsMouseCaptureWithinChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var qBox = sender as ComboBox;
var template = qBox.Template;
var txtBox = template.FindName("PART_EditableTextBox", qBox) as TextBox;
var txtBlock = template.FindName("ContentSite", qBox) as TextBlock;
if (qBox.IsDropDownOpen == false)
{
Keyboard.ClearFocus();
txtBox.Visibility = Visibility.Collapsed;
txtBlock.Visibility = Visibility.Visible;
qBox.ItemsSource = _presentationQuantities;
flag = true;
}
}
That solved the problem and now it's working great, that property was set to the ComboBox.
The goal is to check the state of parameters, the state of each parameter can take the enum value (lock, unlock, or valueIncorrect). The display
will be different according to the state of the parameter(e.g, lock rectangle will be red, unlock the text will be bold and vallueIncorrect will be gray).
In main class we have different parameters VarA, VarB and VarC for example. The state of each parameter can be different.
enum State{lock, unlock, valueIncorrect};
State VarA = lock
State VarB = unlock
State VarC = lock
before I was this style and a rectangle based on this style and When I pressed a button , the style will change, but the reaction will be the same on all parameter
<Style x:Key="DisplayLockGroup" TargetType="GroupBox">
<Setter Property="BorderThickness" Value="2"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Source={x:Static local:LockMgt.Instance}, Path=isLocked}" Value="true">
<Setter Property="BorderBrush" Value="Red" />
</DataTrigger>
<DataTrigger Binding="{Binding Source={x:Static local:LockMgt.Instance}, Path=isLocked}" Value="false">
<Setter Property="BorderBrush" Value="Green" />
</DataTrigger>
</Style.Triggers>
</Style>
<Rectangle x:Name="r_LockEcuTypes" Grid.Row="5" Grid.RowSpan="3" Grid.Column ="1" Grid.ColumnSpan="7" Style="{DynamicResource DisplayLockRectangleGroup}" />
Now i would like to change this behavior, I have different parameter and I would like to individually check the state of this parameter and apply one style according to the value, but i don't know How I can do it.
E.g for one parameter:
State VarA=lock => i would like to apply the style1
State VarB=unlock => i would like to apply the style2
State VarC=lock => i would like to apply the style1 but if the value change from lock to unlock, I would like to apply the style2
I don't know how create the XAML to display correctly what is expected.
As commented, depending on your actual needs, you have several options.
Converter from State to some property value
Change the properties via Style.Triggers (similar to your current approach)
Wrap your control and exchange inner styles via ControlTemplate.Triggers on the wrapper control
The following example is presenting three rectangles (rect1, rect2 and rect3 representing the approach with the same number) and a button that is responsible for changing the State of the ViewModel object in order to show how each rectangle reacts.
The XAML
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication2"
Title="MainWindow" Height="350" Width="525"
Loaded="Window_Loaded">
<Window.Resources>
<!-- Used for 1. -->
<local:StateToBorderBrushConverter x:Key="stateConverter"/>
<!-- Used for 2. -->
<Style x:Key="DisplayLockGroup" TargetType="Rectangle">
<Setter Property="StrokeThickness" Value="2"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Data1State}" Value="{x:Static local:State.locked}">
<Setter Property="Stroke" Value="Red" />
</DataTrigger>
<DataTrigger Binding="{Binding Data1State}" Value="{x:Static local:State.unlock}">
<Setter Property="Stroke" Value="Green" />
</DataTrigger>
</Style.Triggers>
</Style>
<!-- Used for 3. -->
<Style x:Key="DefaultRectangleStyle" TargetType="Rectangle">
<Setter Property="StrokeThickness" Value="2"/>
</Style>
<Style x:Key="LockedRectangleStyle" TargetType="Rectangle">
<Setter Property="StrokeThickness" Value="2"/>
<Setter Property="Stroke" Value="Red" />
</Style>
<Style x:Key="UnlockedRectangleStyle" TargetType="Rectangle">
<Setter Property="StrokeThickness" Value="2"/>
<Setter Property="Stroke" Value="Green" />
</Style>
</Window.Resources>
<Grid x:Name="grid1">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Rectangle x:Name="rect1" Grid.Row="0" Margin="5" StrokeThickness="2" Stroke="{Binding Data1State,Converter={StaticResource stateConverter}}" />
<Rectangle x:Name="rect2" Grid.Row="1" Margin="5" Style="{StaticResource DisplayLockGroup}" />
<ContentControl Margin="5" Grid.Row="2">
<ContentControl.Template>
<ControlTemplate TargetType="ContentControl">
<Rectangle x:Name="rect3" Style="{StaticResource DefaultRectangleStyle}" />
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding Data1State}" Value="{x:Static local:State.locked}">
<Setter TargetName="rect3" Property="Style" Value="{StaticResource LockedRectangleStyle}"/>
</DataTrigger>
<DataTrigger Binding="{Binding Data1State}" Value="{x:Static local:State.unlock}">
<Setter TargetName="rect3" Property="Style" Value="{StaticResource UnlockedRectangleStyle}"/>
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</ContentControl.Template>
</ContentControl>
<Button x:Name="ChangeStateButton" Grid.Row="3" Margin="5" VerticalAlignment="Center" Content="Change State" Click="ChangeStateButton_Click"/>
</Grid>
</Window>
The Code
namespace WpfApplication2
{
public enum State
{
locked,
unlock,
valueIncorrect
}
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged([CallerMemberName] string prop = null)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(prop));
}
}
}
public class MyData : BaseViewModel
{
private State _Data1State;
public State Data1State
{
get { return _Data1State; }
set
{
if (_Data1State != value)
{
_Data1State = value;
NotifyPropertyChanged();
}
}
}
}
public class StateToBorderBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is State)
{
var s = (State)value;
switch (s)
{
case State.locked:
return new SolidColorBrush(Colors.Red);
case State.unlock:
return new SolidColorBrush(Colors.Green);
case State.valueIncorrect:
return new SolidColorBrush(Colors.White);
default:
break;
}
}
return new SolidColorBrush(Colors.Transparent);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private MyData ContextData;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ContextData = new MyData { Data1State = State.locked };
grid1.DataContext = ContextData;
}
private void ChangeStateButton_Click(object sender, RoutedEventArgs e)
{
switch (ContextData.Data1State)
{
case State.locked:
ContextData.Data1State = State.unlock;
break;
case State.unlock:
ContextData.Data1State = State.valueIncorrect;
break;
case State.valueIncorrect:
ContextData.Data1State = State.locked;
break;
default:
ContextData.Data1State = State.locked;
break;
}
}
}
}
Pros and cons:
The converter approach is useful, if the same property type is targeted in many different control types. The converter is returning a Brush and it doesn't care whether that brush will be used in a Rectangle.Stroke, a Border.BorderBrush or some other context.
The style trigger approach is less flexible regarding the targeted control type, but it is easier to maintain changes of more than a single property based on the status.
The control template trigger approach is useful in some advanced scenarios. It allows separate definition of the styles for each state. However, I'd only recommend it if you actually derive your own custom control with additional functionality, not as an ad-hoc control template just for switching styles.
You can apply an enum to color converter in the XAML binding
Background="{Binding Source=StateValue,
Converter={StaticResource stateValueColorConverter}}"
You'll easily find the detailed documentation: this is to give you the main idea of the usage.
Thanks to grek40, it is exactly what I want. I have try the option 3 and 2 and it works fine, I have use the case 2, it is most easily to implement.
I have use the same behavior for add an image on lock and unlock state.
In the Xaml.cs file, How I can access to parameter rect3 on your proposal, when I try it I have compilation error "the name "rect3" does not exist in the current view, I have written
XAML.CS :
rect3.Visibility = Visibility.Collapsed;
XAML :
<ContentControl Grid.RowSpan="3" Grid.ColumnSpan="3" KeyboardNavigation.IsTabStop="False">
<ContentControl.Template>
<ControlTemplate TargetType="ContentControl">
<Rectangle x:Name="rect3" Style="{StaticResource DefaultRectangleStyle}" />
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding Data1State}" Value="{x:Static local:State.locked}">
<Setter TargetName="rect3" Property="Style" Value="{StaticResource LockedRectangleStyle}"/>
</DataTrigger>
<DataTrigger Binding="{Binding Data1State}" Value="{x:Static local:State.unlock}">
<Setter TargetName="rect3" Property="Style" Value="{StaticResource UnlockedRectangleStyle}"/>
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</ContentControl.Template>
</ContentControl>
do you see anything wrong with this trigger?
<Border Margin="2" BorderBrush="#6593CF" BorderThickness="1.5" >
<Border.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding IsCreating, UpdateSourceTrigger=PropertyChanged}" Value="true">
<Setter Property="Border.BorderBrush" Value="Lime"/>
<Setter Property="Border.BorderThickness" Value="3" />
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
</Border>
It is bound to this property:
private bool _IsCreating = false;
public bool IsCreating
{
get
{
return _IsCreating;
}
set
{
if (_IsCreating == value)
{
return;
}
_IsCreating = value;
RaisePropertyChanged("IsCreating");
}
}
When I set IsCreating = true, the style does not update.
You have set BorderBrush and BorderThinkness inline on your border. Inline declaration has quite hight precedence and override your trigger. Remove your inline declaration from border and move it to trigger:
<Border Margin="2">
<Border.Style>
<Style TargetType="{x:Type Border}">
<Style.Triggers>
<DataTrigger
Binding="{Binding Path=DataContext.IsCreating, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
Value="true">
<Setter Property="BorderBrush" Value="Lime" />
<Setter Property="BorderThickness" Value="3" />
</DataTrigger>
<DataTrigger
Binding="{Binding Path=DataContext.IsCreating, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
Value="false">
<Setter Property="BorderBrush" Value="#6593CF" />
<Setter Property="BorderThickness" Value="1.5" />
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<CheckBox IsChecked="{Binding IsCreating}" />
</Border>
I have 2 ContentPresenter fixedContentPresenter and resizableContentPresenter and obviously a Content in Generic.xaml. How can i set the Content to be only in fixedContentPresenter when FixedContent = true; and Content to be only in resizableContentPresenter when FixedContent = false;
I tried changing the content in the code but the content is not showing.
Xaml:
<Grid>
<ContentPresenter x:Name="fixedContent"/>
<Grid>
<ContentPresenter x:Name="resizableContent"/>
</Grid>
</Grid>
Use an implicit style on the content presenters to either hide or show a specific presenter depending on the value of FixedContent
<Style TargetType={x:Type ContentPresenter } x:Key="HideOrShow">
<Style.Triggers>
<DataTrigger Binding="{Binding FixedContent}" Value="False">
<Setter Property="Visibility" Value="Hidden"/>
</DataTrigger>
</Style.Triggers>
</Style>
You should use ContentControl here instead of ContentPresenter.
When FixedContent values changes, Content becomes null, so no Animation related side-effects.
<Grid Background="Purple">
<ContentControl x:Name="fixedContent" Margin="0,75,0,0">
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Style.Triggers>
<DataTrigger Binding="{Binding FixedContent, Mode=OneWay}" Value="false">
<DataTrigger.Setters>
<Setter Property="Content" Value="{StaticResource ContentKey}"/>
</DataTrigger.Setters>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
<Grid Background="Red" Margin="0,54,0,0">
<ContentControl x:Name="resizableContent" Margin="0,75,0,0">
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Style.Triggers>
<DataTrigger Binding="{Binding FixedContent, Mode=OneWay}" Value="true">
<DataTrigger.Setters>
<Setter Property="Content" Value="{StaticResource ContentKey}"/>
</DataTrigger.Setters>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</Grid>
</Grid>
After a day of struggle, I finally found a better answer than that proposed by #OmegaMan, let's hope it help others. Here's the new XAML (added Content="{x:Null}" to both ContentPresenter):
<Grid>
<ContentPresenter x:Name="fixedContent" Content="{x:Null}"/>
<Grid>
<ContentPresenter x:Name="resizableContent" Content="{x:Null}"/>
</Grid>
</Grid>
And the FixedContent logic:
public bool FixedContent
{
get { return (bool)GetValue(FixedContentProperty); }
set
{
SetValue(FixedContentProperty, value);
if (value) // Is Fixed
{
ResizableContentPresenter.Content = null;
FixedContentPresenter.Content = Content;
}
else
{
FixedContentPresenter.Content = null;
ResizableContentPresenter.Content = Content;
}
}
}
I'm trying to create a prompt text label in the background of a TextBox using attached properties, but I can't resolve the binding to the text caption in a style resource:
Style definition:
<Style x:Key="CueBannerTextBoxStyle"
TargetType="TextBox">
<Style.Resources>
<VisualBrush x:Key="CueBannerBrush"
AlignmentX="Left"
AlignmentY="Center"
Stretch="None">
<VisualBrush.Visual>
<Label Content="{Binding Path=(EnhancedControls:CueBannerTextBox.Caption), RelativeSource={RelativeSource AncestorType={x:Type TextBox}}}"
Foreground="LightGray"
Background="White"
Width="200" />
</VisualBrush.Visual>
</VisualBrush>
</Style.Resources>
<Style.Triggers>
<Trigger Property="Text"
Value="{x:Static sys:String.Empty}">
<Setter Property="Background"
Value="{DynamicResource CueBannerBrush}" />
</Trigger>
<Trigger Property="Text"
Value="{x:Null}">
<Setter Property="Background"
Value="{DynamicResource CueBannerBrush}" />
</Trigger>
<Trigger Property="IsKeyboardFocused"
Value="True">
<Setter Property="Background"
Value="White" />
</Trigger>
</Style.Triggers>
</Style>
Attached property:
public class CueBannerTextBox
{
public static String GetCaption(DependencyObject obj)
{
return (String)obj.GetValue(CaptionProperty);
}
public static void SetCaption(DependencyObject obj, String value)
{
obj.SetValue(CaptionProperty, value);
}
public static readonly DependencyProperty CaptionProperty =
DependencyProperty.RegisterAttached("Caption", typeof(String), typeof(CueBannerTextBox), new UIPropertyMetadata(null));
}
Usage:
<TextBox x:Name="txtProductInterfaceStorageId"
EnhancedControls:CueBannerTextBox.Caption="myCustomCaption"
Width="200"
Margin="5"
Style="{StaticResource CueBannerTextBoxStyle}" />
The idea is that you can define the text prompt used in the visual brush when you create the textbox, but I'm getting a binding error:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.TextBox', AncestorLevel='1''. BindingExpression:Path=(0); DataItem=null; target element is 'Label' (Name=''); target property is 'Content' (type 'Object')
The code works fine if I just hardcode the Label.Content property in the style.
Any ideas?
The problem here has to do with the way Style works: basically, one "copy" of the Style will be created (at first reference), and at that point, there may be multiple TextBox controls you want this Style applied to - which one will it use for the RelativeSource?
The (probable) answer is to use a Template instead of a Style - with a control or data template, you'll be able to access the visual tree of the TemplatedParent, and that should get you where you need to be.
EDIT: On further thought, I may be incorrect here...I'll throw together a quick test harness when I'm back in front of a computer and see if I can prove/disprove this.
FURTHER EDIT: While what I originally said was arguably "true", that's not your problem; What Raul said re: the visual tree is correct:
You are setting the Background property on the TextBox to a VisualBrush instance.
The Visual of that brush is not mapped into the Visual Tree of the control.
As a result, any {RelativeSource FindAncestor} navigation will fail, as the parent of that visual will be null.
This is the case regardless of whether it is declared as a Style or a ControlTemplate.
All that said, relying on ElementName definitely is non-ideal, as it reduces the reusability of the definition.
So, what to do?
I've been wracking my brain overnight trying to think of a way to marshal over the proper inheritance context to the contained brush, with little success...I did come up with this super-hacky way, however:
First, the helper property (note: I don't usually style my code this way, but trying to save space):
public class HackyMess
{
public static String GetCaption(DependencyObject obj)
{
return (String)obj.GetValue(CaptionProperty);
}
public static void SetCaption(DependencyObject obj, String value)
{
Debug.WriteLine("obj '{0}' setting caption to '{1}'", obj, value);
obj.SetValue(CaptionProperty, value);
}
public static readonly DependencyProperty CaptionProperty =
DependencyProperty.RegisterAttached("Caption", typeof(String), typeof(HackyMess),
new FrameworkPropertyMetadata(null));
public static object GetContext(DependencyObject obj) { return obj.GetValue(ContextProperty); }
public static void SetContext(DependencyObject obj, object value) { obj.SetValue(ContextProperty, value); }
public static void SetBackground(DependencyObject obj, Brush value) { obj.SetValue(BackgroundProperty, value); }
public static Brush GetBackground(DependencyObject obj) { return (Brush) obj.GetValue(BackgroundProperty); }
public static readonly DependencyProperty ContextProperty = DependencyProperty.RegisterAttached(
"Context", typeof(object), typeof(HackyMess),
new FrameworkPropertyMetadata(default(HackyMess), FrameworkPropertyMetadataOptions.OverridesInheritanceBehavior | FrameworkPropertyMetadataOptions.Inherits));
public static readonly DependencyProperty BackgroundProperty = DependencyProperty.RegisterAttached(
"Background", typeof(Brush), typeof(HackyMess),
new UIPropertyMetadata(default(Brush), OnBackgroundChanged));
private static void OnBackgroundChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
var rawValue = args.NewValue;
if (rawValue is Brush)
{
var brush = rawValue as Brush;
var previousContext = obj.GetValue(ContextProperty);
if (previousContext != null && previousContext != DependencyProperty.UnsetValue)
{
if (brush is VisualBrush)
{
// If our hosted visual is a framework element, set it's data context to our inherited one
var currentVisual = (brush as VisualBrush).GetValue(VisualBrush.VisualProperty);
if(currentVisual is FrameworkElement)
{
(currentVisual as FrameworkElement).SetValue(FrameworkElement.DataContextProperty, previousContext);
}
}
}
// Why can't there be just *one* background property? *sigh*
if (obj is TextBlock) { obj.SetValue(TextBlock.BackgroundProperty, brush); }
else if (obj is Control) { obj.SetValue(Control.BackgroundProperty, brush); }
else if (obj is Panel) { obj.SetValue(Panel.BackgroundProperty, brush); }
else if (obj is Border) { obj.SetValue(Border.BackgroundProperty, brush); }
}
}
}
And now the updated XAML:
<Style x:Key="CueBannerTextBoxStyle"
TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="TextBox.Text"
Value="{x:Static sys:String.Empty}">
<Setter Property="local:HackyMess.Background">
<Setter.Value>
<VisualBrush AlignmentX="Left"
AlignmentY="Center"
Stretch="None">
<VisualBrush.Visual>
<Label Content="{Binding Path=(local:HackyMess.Caption)}"
Foreground="LightGray"
Background="White"
Width="200" />
</VisualBrush.Visual>
</VisualBrush>
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsKeyboardFocused"
Value="True">
<Setter Property="local:HackyMess.Background"
Value="White" />
</Trigger>
</Style.Triggers>
</Style>
<TextBox x:Name="txtProductInterfaceStorageId"
local:HackyMess.Caption="myCustomCaption"
local:HackyMess.Context="{Binding RelativeSource={RelativeSource Self}}"
Width="200"
Margin="5"
Style="{StaticResource CueBannerTextBoxStyle}" />
<TextBox x:Name="txtProductInterfaceStorageId2"
local:HackyMess.Caption="myCustomCaption2"
local:HackyMess.Context="{Binding RelativeSource={RelativeSource Self}}"
Width="200"
Margin="5"
Style="{StaticResource CueBannerTextBoxStyle}" />
The problem is that the Label inside the VisualBrush is not a visual child of the TextBox, that is the reason why that binding doesn't work. My solution for that problem will be using the ElementName binding. But the visual brush you are creating is inside a Style's dictionary resource and then the ElementName binding will not work because doesn't find the element id. The solution for that will be to create the VisualBrush in a global dictionary resources. See this XAML code for delcaring the VisualBrush:
<Window.Resources>
<VisualBrush x:Key="CueBannerBrush"
AlignmentX="Left"
AlignmentY="Center"
Stretch="None">
<VisualBrush.Visual>
<Label Content="{Binding Path=(EnhancedControls:CueBannerTextBox.Caption), ElementName=txtProductInterfaceStorageId}"
Foreground="#4F48DD"
Background="#B72121"
Width="200"
Height="200" />
</VisualBrush.Visual>
</VisualBrush>
<Style x:Key="CueBannerTextBoxStyle"
TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Text"
Value="{x:Static System:String.Empty}">
<Setter Property="Background"
Value="{DynamicResource CueBannerBrush}" />
</Trigger>
<Trigger Property="Text"
Value="{x:Null}">
<Setter Property="Background"
Value="{DynamicResource CueBannerBrush}" />
</Trigger>
<Trigger Property="IsKeyboardFocused"
Value="True">
<Setter Property="Background"
Value="White" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
This code should works. No more code need to be changed so I'm not rewriting all the code.
Hope this solution works for you...