I am pretty new with WPF and am doing some custom control stuff...
My problem is that the code in one file is going to be way to much, so i want
to split the code in seperate files, so other people looking in that code aren´t going to be overwhelmed.
Okay to my question...
I got a ResourceDictionary... the "Generic.xaml"
In this file a got the template of an DataGrid:
<Style TargetType="{x:Type local:BADataGrid}">
<Style.Setters>
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate TargetType="local:BADataGrid">
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}"
Padding="{TemplateBinding Padding}"
SnapsToDevicePixels="True">
<!-- *SOME TEMPLATE CODE* -->
</Border>
<ControlTemplate.Triggers>
<Trigger Property="GridStyle" Value="CUSTOMER">
<Trigger.Setters>
<Setter Property="ColumnHeaderStyle">
<Setter.Value>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Background">
<Setter.Value>
<ImageBrush>
<ImageBrush.ImageSource>
<Binding Path="HeaderBackground" RelativeSource="{RelativeSource AncestorType=local:BADataGrid}">
<Binding.TargetNullValue>
<ImageSource>
headerBack.png
</ImageSource>
</Binding.TargetNullValue>
</Binding>
</ImageBrush.ImageSource>
</ImageBrush>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
</Trigger.Setters>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style.Setters>
</Style>
Now I want the "ControlTemplate.Triggers" part of the code above in another .XAML File.
Is this even possible?
it´s me again. Sorry it took me so long to answer.
I am a few steps ahead now... I got the Trigger in an additional ResourceDictionary, and if I impletment it in the "Window.Resources" where I implement the control everything works just fine.
My problem now is... I don´t want to implement the ResourceDictionary in the "Window.Resources" but in the "ControlTemplate.Resources" of my custom control. But when I do so it tell´s me :
"Unable to cast object of type 'Microsoft.Expression.Markup.DocumentModel.DocumentCompositeNode' to type 'System.Windows.ResourceDictionary'.
<ControlTemplate.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary
Source="Customer.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</ControlTemplate.Resources>
If I copy the code inside the Customer.xaml ResourceDictionary into the ControlTemplate.Resources it works... but I want it in an additional file...
Any ideas?
Look into Resource Dictionaries. That should allow you to split styles across files.
Did it with a nasty workaround... I´ll just share it with you.
I just implemented an event that is fired when the DataGrid is loaded.
In this event I load the ResourceDictionarys i wanted to add to the control template
in ResourceDictionary object´s. Then i iterate through all entrys in the ResourceDictionary object and add each seperate to the ControlTemplate´s resources...
Here´s the code:
void DataGridLoaded(object sender, RoutedEventArgs e)
{
BADataGrid dg = (BADataGrid)VisualTreeHelper.GetParent((DependencyObject)sender);
List<string> resourceList = new List<string>();
resourceList.Add(Properties.Resources.Customer);
foreach (string s in resourceList)
{
System.Xml.XmlReader xmlReader = new System.Xml.XmlTextReader(new System.IO.StringReader(s));
ResourceDictionary resource = (ResourceDictionary)XamlReader.Load(xmlReader);
foreach (System.Collections.DictionaryEntry item in resource)
{
dg.Resources.Add(item.Key, item.Value);
}
}
Related
This is a best practices question regarding wpf themeing and more specifically skinning.
This is more of an opinion based question since I don't have a problem making this work but more of a general wondering if my conclusions cover all the scenarios, and if any one else came across the same thoughts on the issue and what was their approach .
Some background, Our team is required to define a way to give our system the ability to be themeable.
We broke this ability down to 2 categories :
1) The styles of our controls which we simply call 'Theme'.
2) The resources they use to customize their appearance called 'Skin' this includes Brushes , and all sorts of sizing structs like CornerRadius , BorderThickness etc.
The way which a Skin is set for the system is a simple case of merging the skin dictionary last into our app's resources.
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Default.skin.xaml" />
<ResourceDictionary Source="Theme.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
A different skin being merged last into our app.
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
string skin = e.Args[0];
if (skin == "Blue")
{ .
ResourceDictionary blueSkin = new ResourceDictionary();
blueSkin.Source = new Uri("Blue.skin.xaml", UriKind.Relative);
Application.Current.Resources.MergedDictionaries.Add(blueSkin);
}
}
Inside Theme.xaml :
<!-- Region TextBox ControlTemplate -->
<ControlTemplate TargetType="{x:Type TextBox}" x:Key="TextBoxTemplate">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="{StaticResource TextBoxCornerRadius}" >
<Border x:Name="shadowBorder" BorderBrush="{StaticResource TextBoxShadowBrush}"
CornerRadius="{StaticResource TextBoxInnerShadowCornerRadius}"
BorderThickness="{StaticResource TextBoxInnerShadowBorderThickness}"
Margin="{StaticResource TextBoxInnerShadowNegativeMarginForShadowOverlap}" >
<ScrollViewer x:Name="PART_ContentHost" Padding="{TemplateBinding Padding}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" />
</Border>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="BorderThickness" Value="0">
<Setter TargetName="shadowBorder" Property="BorderThickness" Value="0" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
<!-- EndRegion -->
<!-- Region TextBox Style -->
<Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}">
<Setter Property="BorderBrush" Value="{StaticResource TextBoxBorderBrush}" />
<Setter Property="Background" Value="{StaticResource TextBoxBackgroundBrush}" />
<Setter Property="BorderThickness" Value="{StaticResource TextBoxBorderThickness}" />
<Setter Property="Padding" Value="{StaticResource TextBoxPadding}" />
<Setter Property="Template" Value="{StaticResource TextBoxTemplate}"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{StaticResource TextBoxIsMouseOverBackgroundBrush}" />
<Setter Property="BorderBrush" Value="{StaticResource TextBoxIsMouseOverBorderBrush}" />
</Trigger>
<Trigger Property="IsFocused" Value="True">
<Setter Property="Background" Value="{StaticResource TextBoxIsMouseWithinBackgroundBrush}" />
<Setter Property="BorderBrush" Value="{StaticResource TextBoxIsMouseWithinBorderBrush}" />
</Trigger>
</Style.Triggers>
</Style>
<!-- EndRegion -->
In the TextBox ControlTemplate there are elements bound to DependencyProperties using TemplateBinding and some like the CornerRadius and InnerCornerRadius, InnerBorderThickness and InnerBorderBrush which are given their value from resources.
What would be the best approach ?
creating a derived control with the relevant Dependency properties
which would reference the relevant resources and then have the elements in the control template bind to them.
Or
have the elements inside the template reference these resources themselves.
Using the Dependency Property approach :
Advantages :
1) Clarity, we have a clearer API for our control and better understanding of how our control looks and behaves the way it does.
2) The template does not have to change in order to be customizable. Everything is controlled via style.
3) Triggers as well change the look and feel of the control without the need to override the control template, no need for ControlTemplate triggers.
4) "Blendabilty" using blend i can much easily customize my control.
5) Styles themselves are inheritable. so if i want to change just one aspect of the control all i need to do is inherit from the default style.
Disadvantages :
1) Implementing yet another custom control.
2) Implementing numerous dependency properties, some of which do not have much to do with the control and are only there to satisfy something we have in our template.
Just to clarify this means inheriting from TextBox something like InnerShadowTextBox and
implementing dependency properties with in it for all the above.
This will intensify if I have numerous elements inside my template which have to be customizable.
Something like this monstrosity:
<Style x:Key="{x:Type cc:ComplexControl}" TargetType="{x:Type cc:ComplexControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type cc:ComplexControl}">
<Grid>
<Ellipse Fill="Red" Margin="0" Stroke="Black" StrokeThickness="1"/>
<Ellipse Fill="Green" Margin="6" Stroke="Red" StrokeThickness="1"/>
<Ellipse Fill="Blue" Margin="12"/>
<Ellipse Fill="Aqua" Margin="24" />
<Ellipse Fill="Beige" Margin="32"/>
<StackPanel Orientation="Horizontal" Width="25" Height="25"
VerticalAlignment="Center" HorizontalAlignment="Center">
<Rectangle Fill="Black" Width="2" />
<Rectangle Fill="Black" Width="2" Margin="2,0,0,0"/>
<Rectangle Fill="Black" Width="2" Margin="2,0,0,0"/>
<Rectangle Fill="Black" Width="2" Margin="2,0,0,0"/>
</StackPanel>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Which would require numerous resources :
<SolidColorBrush x:Key="Ellipse1Fill">Red</SolidColorBrush>
<SolidColorBrush x:Key="Ellipse2Fill">Green</SolidColorBrush>
<SolidColorBrush x:Key="Ellipse3Fill">Blue</SolidColorBrush>
<SolidColorBrush x:Key="Ellipse4Fill">Aqua</SolidColorBrush>
<SolidColorBrush x:Key="Ellipse5Fill">Beige</SolidColorBrush>
<SolidColorBrush x:Key="Ellipse1Stroke">Beige</SolidColorBrush>
<sys:Double x:Key="Ellipse1StrokeThickness>1</sys:Double>
......... and many more
I would have a large list of resources either way. But with dependency properties.
I would also need to assign need to find meaning in every little part,Which sometimes isn't much more then "it looks good" and does not have much to do with the control or What if tomorrow I would want to change the template.
Using the approach where the resources are referenced from within the control template.
Advantages :
1) Easy to use, side steps the ugliness describes in the disadvantages described above in the Dp approach while providing a "hack" that enables a theme.
Disadvantages :
1) If I would want to further customize my control like add a trigger that influences the inner border of my TextBox I would simply have to create a new control template.
2) Not a clear API, Lets say I would like to change the BorderBrush of the inner border in a specific view.
<TextBox>
<TextBox.Resources>
<SolidColorBrush x:Key="InnerBorderBrush" Color="Red" />
</TextBox.Resources>
</TextBox>
Which isn't that bad come to think about it…
we sometimes do this with Selector implementations which internally use the specific resources when getting rid of the inactive selection and hightlight colors like so :
<ListBox>
<ListBox.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Transparent"/>
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="Transparent"/>
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightTextBrushKey}" Color="Transparent"/>
</ListBox.Resources>
</ListBox>
Conclusions :
The hybrid described in the TextBox Style above is the way to go.
1) Dependency properties will be introduced only for aspects of the control which relate to the control's logic including specific template part's .
2) The resource names would be comprised by a clear naming convention and separated in files based on the control they relate to and common usages in views,Like Common brushes used in views in our app.
3) Control templates should aspire to be minimalistic and to use existing Dependency properties. Like Background, Foreground, BorderBrush etc.
I would greatly appreciate your input and thoughts on the matter , thanks in advance.
As Xavier said, this might be a better question for Code Review. But I will convey some key thoughts on your question, even though a lot of it will come to personal (or team) style and requirements.
After creating several dozen themes, I would recommend against custom controls whenever possible. Over time, the maintainability goes down quite a bit.
If you require minor modifications to a style, it is better to use DataTemplates and Data Triggers if the situation allows. This way you are changing the style in a clean way.
Additionally, you can leverage the BasedOn property. Create your "base" style and have multiple styles that have the attribute BasedOn="{myBaseStyle}. This will allow you lots of options without cluttering your code.
As a rule of thumb, I always recommend having more brushes/colors/resources as opposed to more styles or templates. We usually have our hierarchy set for colors->brushes->styles->templates. This helps reuse the colors while still maintaining separation via brushes.
Using DynamicResource as opposed to StaticResource is also useful in some situations where you load resources dynamically.
Hope this helps. Would love to write more, but some of the parameters for writing a solid theme is very context specific. If you have further examples, I'd be glad to add more information.
I am trying to create a visual template (saved in resource dictionary as xaml code) for a grid object, that I will apply to various grid objects created later in runtime.
I need a simple style with border and background.
What would be the best way of doing this?
Simple working examples would be greatly appreciated.
Ok, so, after searching for examples, I tried something like this:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="TestStyle">
<Setter Property="Background" Value="#FF873507" />
<Setter.Value>
<ControlTemplate>
<Grid>
<Border BorderThickness="7" CornerRadius="4">
<Border.BorderBrush>
<SolidColorBrush Color="#73B2F5"/>
</Border.BorderBrush>
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Style>
</ResourceDictionary>
WPF doesn't really work like that... because the Grid class has no Template property, you cannot define a new ControlTemplate for it. The nearest thing that you can do is to create a UserControl with the UI elements that you want to use and then display the UserControl wherever you want to display those controls.
Alternatively, you could define your content inside a ControlTemplate if the inner controls will always be the same:
<ControlTemplate x:Key="StaticGrid">
<Grid>
<Border BorderThickness="7" CornerRadius="4">
<Border.BorderBrush>
<SolidColorBrush Color="#73B2F5"/>
</Border.BorderBrush>
<!--Add your inner elements here-->
</Border>
</Grid>
</ControlTemplate>
You could then display it like this:
<ContentControl Template="{StaticResource StaticGrid}" />
However, you wouldn't be able to add different inner elements using this method. If you used the UserControl method, you could potentially replace the word UserControl with Grid so that you were in fact extending the Grid class, but you still wouldn't be able to add different elements to it.
The best that you could do in a Style would be to set the Background property.
After more tries and frustrations, I found a much simpler solution, that worked for me.
Instead of trying to apply the style to the grid, I applied it to the border around the grid.
So, my dictionary looks like this:
<Style x:Key="TestStyle" TargetType="{x:Type Border}">
<Setter Property="Background" Value="#FFBDACA2" />
<Setter Property="BorderBrush" Value="#FFFF5E00" />
<Setter Property="CornerRadius" Value="30,30,30,30" />
<Setter Property="BorderThickness" Value="10" />
</Style>
And my main frame xaml:
<Border Style="{StaticResource TestStyle}" >
<Grid>
</Grid>
</Border>
I need to change the background of the selected item in a list view, programmatically.
The style currently looks like this (as default)
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background">
<Setter.Value>
<ImageBrush ImageSource="images/selection-large.png"/>
</Setter.Value>
</Setter>
</Trigger>
I need to be able to change that background image of the selected item programmatically.
I have attempted to do this myself however i am not really sure how to go about it.
I did notice that the listview has a styles property but other than that i am completely stumped.
I am using VB.net
Edit
Would something like this work? and if so, what am i doing wrong? My listview is completely invisible with this code.
Dim trigger As New Trigger()
trigger.Property = ListViewItem.IsSelectedProperty
trigger.Value = True
trigger.Setters.Add(New Setter(ListViewItem.BackgroundProperty, Brushes.Pink))
mylistview.Style.Triggers.Add(trigger)
mylistview.ItemContainerStyle = Style
Bind your IsSelected property to some bool value in the ViewModel and toggle that.
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
</Style>
</ListView.ItemContainerStyle>
Item ViewModel:
private bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set
{
_isSelected = value;
NotifyPropertyChange("IsSelected");
}
}
In WPF you don't manipulate UI elements in procedural code, instead you use DataBinding and manipulate your models / ViewModels' properties
As an aside, I recommend against using PNG or other bitmap based stuff for regular UI elements in WPF.
Instead of that you should create your UI using WPF elements which are vector-based and thus resolution independent.
You can do this within the XAML, Try this:
<Window.Resources>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListViewItem}">
<Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter Property="Background">
<Setter.Value>
<ImageBrush ImageSource="images/selection-large.png"/>
</Setter.Value>
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
I was able to finally work it out..
All i had to do was make another style based on the first one and give them both different x:keys.. Then i was able to change styles like this.
mylistview.ItemContainerStyle = DirectCast(FindResource("XKeyName"), Style)
I'm trying to write a reusable Template for a WPF ItemContainerStyle.
This Template changes the way the TabControl's Item looks.
This template is meant to be used in several places in the application.
In each place it is used I want to be able to pass different parameters to it.
For example: to change the Margin of the Border of the Item:
<Style x:Key="TabItemStyle1" TargetType="{x:Type TabItem}">
<Setter Property="Margin" Value="10,0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid SnapsToDevicePixels="true">
<Border x:Name="Bd" Width="80"
Background="Gray"
Margin="{TemplateBinding Margin}">
<ContentPresenter x:Name="Content"
ContentSource="Header" />
</Border>
</Grid>
<ControlTemplate.Triggers>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
...
<TabControl ItemContainerStyle="{DynamicResource TabItemStyle1}">
In the place where the style is used I Would like to Write something like:
ItemContainerStyle="{DynamicResource TabItemStyle1 Margin='5,0'}"
or
<TabControl Margin="78,51,167,90" ItemContainerStyle="{DynamicResource TabItemStyle1}"
ItemContainerStyle.Margin="5,0">
The motivation is to use this template in different places with different Margins.
Is there a way to do this ?
Thank you
You can do it with attached properties. I wrote a blog post explaining how to do it:
http://www.thomaslevesque.com/2011/10/01/wpf-creating-parameterized-styles-with-attached-properties/
Another option is to use DynamicResource, and redefine the resource in derived styles
OK, I've found a way to do this with dave's help.
The Solution is to create a derived template and set the properties in it.
This way the original template can be reused.
<Style x:Key="TabItemStyle2" TargetType="{x:Type TabItem}"
BasedOn="{StaticResource TabItemStyle1}">
<Style.Setters>
<Setter Property="Margin" Value="40,0"></Setter>
</Style.Setters>
</Style>
And set the TabControl's ItemContainerStyle to the derived style:
<TabControl ItemContainerStyle="{DynamicResource TabItemStyle2}">
In my case I had to change some parameters deep in the applied template (so I couldn't use just a setter).
And I didn't want to code some classes that traverse the visual tree or register an attached property to do the changes.
However, it is possible to define resources within the base style and override these values in the derived definitions. So, with the original example this would look like this:
<Style x:Key="AbsTabItemStyle" TargetType="{x:Type TabItem}">
<!-- Override these default values in derived style definitions -->
<Style.Resources>
<s:Double x:Key="GridBorderMargin">10</s:Double>
<Color x:Key="GridBorderColor">Grey</Color>
</Style.Resources>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid SnapsToDevicePixels="true">
<Border x:Name="Bd"
Width="80"
Background="{DynamicResouces GridBorderColor}"
Margin="{DynamicResouces GridBorderMargin}"
>
<ContentPresenter x:Name="Content"
ContentSource="Header" />
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="BigMarginTabItemStyle" TargetType="{x:Type TabItem}" BasedOn="{StaticResource AbsTabItemStyle}">
<!-- Set different values in this derived style definition -->
<Style.Resources>
<s:Double x:Key="GridBorderMargin">20</s:Double>
</Style.Resources>
</Style>
<Style x:Key="RedTabItemStyle" TargetType="{x:Type TabItem}" BasedOn="{StaticResource AbsTabItemStyle}">
<!-- Set different values in this derived style definition -->
<Style.Resources>
<c:Color x:Key="GridBorderColor">Red</Color>
</Style.Resources>
</Style>
A way of solving it is by adding a Margin property to the objects/ViewModels you want to display and (data)bind to that value in the template.
As far as I know there is no support of parameterized styles/templates.
Been banging my head against this all morning.
Basically, I have a listbox, and I want to keep people from changing the selection during a long running process, but allow them to still scroll.
Solution:
All the answers were good, I went with swallowing mouse events since that was the most straight forward. I wired PreviewMouseDown and PreviewMouseUp to a single event, which checked my backgroundWorker.IsBusy, and if it was set the IsHandled property on the event args to true.
If you look in to the control template of the ListBox, there is a ScrollBar and ItemsPresenter inside. So Make the ItemsPresenter Disabled and you will get this easily. Use the bellow Style on the ListBox and you are good to go.
<Style x:Key="disabledListBoxWithScroll" TargetType="{x:Type ListBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBox}">
<Border x:Name="Bd" SnapsToDevicePixels="true" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="1">
<ScrollViewer Padding="{TemplateBinding Padding}" Focusable="false">
<ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" IsEnabled="False" IsHitTestVisible="True"/>
</ScrollViewer>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
</Trigger>
<Trigger Property="IsGrouping" Value="true">
<Setter Property="ScrollViewer.CanContentScroll" Value="false"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
On the ListBox use the Style
<ListBox Style="{DynamicResource disabledListBoxWithScroll}" ..... />
I found that putting a disabled ListBox in a ScrollViewer with auto scrolling enabled gives the desired effect.
The trick is to not really disable. Disabling will lock out all messages from the scroll box.
During the long operation, gray out the text in the list box using its .ForeColor property and swallow all mouse clicks. This will simulate disabling the control and allow scrolling unimpeded.
While it's for Silverlight, maybe this blog post would help you get going in the right direction? Silverlight No Selection ListBox and ViewBox
I used this solution, it's really easy and works perfectly:
For every SurfaceListBoxItem item you put in the Listbox, do this:
item.IsHitTestVisible = false;
This worked best for me. It's easy and whole code is in XAML which is IMO very neat.
<ListBox ItemsSource="{Binding MySource}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<DataTrigger Binding="{Binding IsEditing}" Value="True">
<Setter Property="IsEnabled" Value="True"/>
</DataTrigger>
<DataTrigger Binding="{Binding IsEditing}" Value="False">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
Another option worth considering is disabling the ListBoxItems. This can be done by setting the ItemContainerStyle as shown in the following snippet.
<ListBox ItemsSource="{Binding YourCollection}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsEnabled" Value="False" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
If you don't want the text to be grey you can specify the disabled color by adding a brush to the style's resources with the following key: {x:Static SystemColors.GrayTextBrushKey}. The other solution would be to override the ListBoxItem control template.
This question is pretty much the same as this one: There ain't ListBox.SelectionMode=“None”, is there another way to disable selection in a listbox? and my answer is the same.
I found a very simple and straight forward solution working for me, I hope it would do for you as well
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Focusable" Value="False"/>
</Style>
A complete answer using http://www.codeproject.com/Tips/60619/Scrollable-Disabled-ListBox-in-WPF
The Style:
<Style TargetType="{x:Type local:CustomListBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomListBox}">
<Border SnapsToDevicePixels="true" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="1">
<ScrollViewer IsEnabled="True">
<ItemsPresenter IsEnabled="{Binding Path=IsEnabledWithScroll, RelativeSource={RelativeSource TemplatedParent}}" SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}"/>
</ScrollViewer>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
The class
public class CustomListBox : ListBox
{
public bool IsEnabledWithScroll
{
get { return (bool)GetValue(IsEnabledWithScrollProperty); }
set { SetValue(IsEnabledWithScrollProperty, value); }
}
public static readonly DependencyProperty IsEnabledWithScrollProperty =
DependencyProperty.Register("IsEnabledWithScroll", typeof(bool), typeof(CustomListBox), new UIPropertyMetadata(true));
}
Then instead of setted IsEnabled on the ListBox, use IsEnabledWithScroll instead. Scrolling will work if the listbox is enabled or disabled.
There seem to be many ways to skin this particular cat. I found that by setting IsHitTestVisible on the ItemsContainerStyle in XAML I got exactly what I needed:
<ListBox IsHitTestVisible="true" ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.CanContentScroll="True">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsHitTestVisible" Value="False" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
Well, I found a sweet way to provide this feature. What I did is that in the DataTemplate of the listBox I binded the parent layout enable property with the boolean flag using Page as Source.
Step 1 - Provide the x:Name attribute to the page. If the page you are using is extended with base page than make sure that the base page is not an abstract class and has an default constructor without any arguments.
<Page x:Class="OPMS.Views.Registration"
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"
x:Name="MainPage"
d:DesignWidth="1024"
Title="Registration"
>
Step 2 - Use the Page as a source for the DataTemplate parent layout items IsEnabled property
<ListBox Grid.Row="2"
ItemsSource="{Binding TestGroups}"
AlternationCount="2"
Padding="0"
Margin="10,5,10,10"
>
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Name}"
IsChecked="{Binding IsSelected}"
IsEnabled="{Binding Source={x:Reference MainPage}, Path=DataContext.BindingVariableHere}"
/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>