I've created an ItemControl with a dataTemplate that contains a rectangle that will be colorized based of the ItemsSource. The date being fed to my application is a color hex code that does not contain the hash sign (#). Just a 6-character string. To get the color to show up correctly i need to format the 6-character string with the # in front of it. exp #A31F34
Here's the XAML
<DataTemplate x:Key="ColorSequenceSwatchPreviews">
<Rectangle Name="ColorSwatch" Height="20" Width="120" RadiusX="3" RadiusY="3" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="0,3,0,3">
<Rectangle.Style>
<Style TargetType="{x:Type Rectangle}">
<Setter Property="Fill">
<Setter.Value>
<MultiBinding>
<MultiBinding.StringFormat><![CDATA[#{0}]]></MultiBinding.StringFormat>
<Binding Path="InnerXml" Mode="OneWay" />
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
</Rectangle.Style>
</Rectangle>
I'm using a MultiBinding.StringFormat to format the string into a Hexcode properly, but am stumped as to why the fill of the rectangle is not colorizing.
I am able to get the rectangle to colorize if I do the MultiBinding with a TextBox, then bind the rectangle's fill property to the Text property of the textBox. However, I would much prefer binding directly from the rectangle's fill property like in my first example since it is cleaner.
<DataTemplate x:Key="ColorSequenceSwatchPreviews">
<StackPanel Orientation="Horizontal" Margin="0,3,0,3" VerticalAlignment="Center" HorizontalAlignment="Left">
<TextBox x:Name="Hexcode" Visibility="Collapsed">
<TextBox.Text>
<MultiBinding>
<MultiBinding.StringFormat><![CDATA[#{0}]]></MultiBinding.StringFormat>
<Binding Path="InnerXml" Mode="OneWay" />
</MultiBinding>
</TextBox.Text>
</TextBox>
<Rectangle Name="ColorSwatch" Height="20" Width="120" RadiusX="3" RadiusY="3" VerticalAlignment="Center" HorizontalAlignment="Left">
<Rectangle.Style>
<Style TargetType="{x:Type Rectangle}">
<Setter Property="Fill" Value="{Binding ElementName=Hexcode,Path=,Mode=OneWay}" />
</Style>
</Rectangle.Style>
</Rectangle>
</StackPanel>
Is there a way to get the first example to work or am i stuck with using the code from the second example?
This can be achieved far more easily using a Converter. You don't even need MultiBinding for it. Simple Binding with a Converter should do it:
Here is the converter:
<ValueConversion(GetType(String), GetType(SolidColorBrush))>
Public Class HexToBrushConverter
Implements IValueConverter
Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
Return DirectCast(New BrushConverter().ConvertFrom("#" & value.ToString()), SolidColorBrush)
End Function
Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
Return Nothing
End Function
End Class
All you need to do now is to create an object of the converter in your Resources section:
<local:HexToBrushConverter x:Key="HexToBrushConverter" />
(local is the namespace of your project where you define this converter class)
and then use it in the Fill property:
<Rectangle Fill="{Binding ElementName=Hexcode, Path=, Mode=OneWay, Converter={StaticResource HexToBrushConverter}}" />
Related
I'm based on the official Microsoft sample to create a MasterDetail ListView:
MasterDetail ListView UWP sample
I have adapted it to my case, as I want that users can edit directly selected items from the ListView. But I meet a strange comportement:
when I add a new item to the ListView, the changes of the current item, done in the details container, are well saved
but when I select an existing item in the ListView, the changes of the current item, done in the details container, are not saved
Here is a screenshot of my app:
The XAML of my ListView is like this:
<!-- Master : List of Feedbacks -->
<ListView
x:Name="MasterListViewFeedbacks"
Grid.Row="1"
ItemContainerTransitions="{x:Null}"
ItemTemplate="{StaticResource MasterListViewFeedbacksItemTemplate}"
IsItemClickEnabled="True"
ItemsSource="{Binding CarForm.feedback_comments}"
SelectedItem="{Binding SelectedFeedback, Mode=TwoWay}">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>
<ListView.FooterTemplate>
<DataTemplate>
<CommandBar Background="White">
<CommandBar.Content>
<StackPanel Orientation="Horizontal">
<AppBarButton Icon="Add" Label="Add Feedback"
Command="{Binding AddItemFeedbacksCommand}" />
<AppBarButton Icon="Delete" Label="Delete Feedback"
Command="{Binding RemoveItemFeedbacksCommand}" />
</StackPanel>
</CommandBar.Content>
</CommandBar>
</DataTemplate>
</ListView.FooterTemplate>
</ListView>
The XAML of the ListView's ItemTemplate is:
<DataTemplate x:Key="MasterListViewFeedbacksItemTemplate" x:DataType="models:Feedback_Comments">
<StackPanel Margin="0,11,0,13"
Orientation="Horizontal">
<TextBlock Text="{x:Bind creator }"
Style="{ThemeResource BaseTextBlockStyle}" />
<TextBlock Text=" - " />
<TextBlock Text="{x:Bind comment_date }"
Margin="12,1,0,0" />
</StackPanel>
</DataTemplate>
The XAML of the Details container is like this:
<!-- Detail : Selected Feedback -->
<ContentPresenter
x:Name="DetailFeedbackContentPresenter"
Grid.Column="1"
Grid.RowSpan="2"
BorderThickness="1,0,0,0"
Padding="24,0"
BorderBrush="{ThemeResource SystemControlForegroundBaseLowBrush}"
Content="{x:Bind MasterListViewFeedbacks.SelectedItem, Mode=OneWay}">
<ContentPresenter.ContentTemplate>
<DataTemplate x:DataType="models:Feedback_Comments">
<StackPanel Visibility="{Binding FeedbacksCnt, Converter={StaticResource CountToVisibilityConverter}}">
<TextBox Text="{Binding creator, Mode=TwoWay}" />
<DatePicker Date="{Binding comment_date, Converter={StaticResource DateTimeToDateTimeOffsetConverter}, Mode=TwoWay}"/>
<TextBox TextWrapping="Wrap" AcceptsReturn="True" IsSpellCheckEnabled="True"
Text="{Binding comment, Mode=TwoWay}" />
</StackPanel>
</DataTemplate>
</ContentPresenter.ContentTemplate>
<ContentPresenter.ContentTransitions>
<!-- Empty by default. See MasterListView_ItemClick -->
<TransitionCollection />
</ContentPresenter.ContentTransitions>
</ContentPresenter>
The "CarForm" is the main object of my ViewModel. Each CarForm contains a List of "Feedback_Comments".
So in my ViewModel, I do this when I add a new comment:
private void AddItemFeedbacks()
{
FeedbacksCnt++;
CarForm.feedback_comments.Add(new Feedback_Comments()
{
sequence = FeedbacksCnt,
creator_id = user_id,
_creator = username,
comment_date = DateTime.Now
});
SelectedFeedback = CarForm.feedback_comments[CarForm.feedback_comments.Count - 1];
}
=> the changes done in the Feedback_Comment that was edited before the add are well preserved
I don't do anything when the user select an existing Feedback_Comment: this is managed by the XAML directly.
=> the changes done in the Feedback_Comment that was edited before to select anoter one are not preserved
=> Would you have any explanation?
The TwoWay binding for the Text property is updated only when the TextBox loses focus. However, when you select a different item in the list, the contents of the TextBox are no longer bound to the original item and so are not updated.
To trigger the update each time the Text contents change, so that the changes are reflected immediately, set the UpdateSourceTrigger set to PropertyChanged:
<TextBox Text="{Binding comment, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
Triggering changes everywhere
To ensure your changes are relflected everywhere including the list, you will need to do two things.
First, your feedback_comments is of type ObservableCollection<Feedback_Comments>. This ensures that the added and removed items are added and removed from the ListView.
Second, the Feedback_Comments class must implement the INotifyPropertyChanged interface. This interface is required to let the user interface know about changes in the data-bound object properties.
Implementing this interface is fairly straightforward and is described for example on MSDN.
The quick solution looks like this:
public class Feedback_Comments : INotifyPropertyChanged
{
// your code
//INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged( [ CallerMemberName ]string propertyName = "" )
{
PropertyChanged?.Invoke( this, new PropertyChangedEventArgs( propertyName ) );
}
}
Now from each of your property setters call OnPropertyChanged(); after setting the value:
private string _comment = "";
public string Comment
{
get
{
return _comment;
}
set
{
_comment = value;
OnPropertyChanged();
}
}
Note, that the [CallerMemberName] attribute tells the compiler to replace the parameter by the name of the caller - in this case the name of the property, which is exactly what you need.
Also note, that you can't use simple auto-properties in this case (because you need to call the OnPropertyChanged method.
Bonus
Finally as a small recommendation, I see you are using C++-like naming conventions, which does not fit too well into the C# world. Take a look at the recommended C# naming conventions to improve the code readability :-) .
This is trivial thing but yet it does not work.
I have something like this (it is in its own folder)
<ResourceDictionary>
<Path x:Key="Test"
Stroke="Black"
Fill="Gray"
Data="M 10,100 C 10,300 300,-200 300,100" />
</ResourceDictionary>
Now I want to use it
<Page>
<Page.Resources>
<ResourceDictionary>
<ResourceDictionary.MergeDictionaries>
<ResourceDictionary Source="MyFolder/MyResourceDictionary.xaml/>
</ResourceDictionary.MergeDictionaries>
</ResourceDictionary>
</Page.Resources>
<ContentPresenter Content="{StaticResource Test}"/>
<Page/>
This will throw an exception, but I don't understand why. Exactly the same scenario in wpf works fine.
What about this solution?
Declare your GeometryData
<x:String x:Key="TestPathGeomerty">M 10,100 C 10,300 300,-200 300,100</x:String>
And use Path, instead ContentPresenter
<Path Data="{StaticResource TestPathGeomerty}"
Fill="Red"/>
The Path.Data property is of type Geometry so define it as a Geometry instead of a string
<Geometry x:Key="TestPathGeomerty">M 10,100 C 10,300 300,-200 300,100</Geometry>
<Path Data="{StaticResource TestPathGeomerty}"
Fill="Red"/>
In WPF, you can share the same instance within multiple controls. Unfortunately this is not possible in UWP.
The only solution that is guaranteed to work in UWP, is to define a DataTemplate in your resource containing the icon.
It is also better to use PathIcon instead of Path. PathIcon makes use of the Foreground property that will be inherited from your parent controls.
Here's an example on how to share Data paths for icons that will automatically scale (by using a Viewbox).
<Page.Resources>
<DataTemplate x:Key="MagnifyingGlassPathIconCT">
<Viewbox Stretch="Uniform">
<PathIcon Data="M44,12 C32,12 22,22 22,34 22,46 32,56 44,56 56,56 66,46 66,34 66,22 56,12 44,12z M44,0 C63,0 78,15 78,34 78,53 63,68 44,68 40,68 36.5,67.5 33,66 L32.5,66 14,90 0,79.5 18,55.5 17,55 C13,49 10,42 10,34 10,15 25,0 44,0z" />
</Viewbox>
</DataTemplate>
</Page.Resources>
<StackPanel Padding="40" HorizontalAlignment="Left">
<!-- Plain icon -->
<ContentPresenter
Width="40"
Height="40"
ContentTemplate="{StaticResource MagnifyingGlassPathIconCT}"
Foreground="Purple" />
<!-- Icon with a border -->
<Border
Width="40" Padding="7"
Height="40"
BorderBrush="Black"
BorderThickness="2">
<ContentPresenter ContentTemplate="{StaticResource MagnifyingGlassPathIconCT}" Foreground="Red" />
</Border>
<!-- Icon in a normal Button -->
<Button
Width="40"
Height="40"
ContentTemplate="{StaticResource MagnifyingGlassPathIconCT}"
Foreground="RoyalBlue" />
<!-- Icon in an AppBarButton -->
<AppBarButton
Width="40"
ContentTemplate="{StaticResource MagnifyingGlassPathIconCT}"
Foreground="Black"
Label="Search" />
</StackPanel>
For a solution that lets you define it in a Style, try writting an attached property like this:
public static string GetPathData(DependencyObject obj)
{
return (string)obj.GetValue(PathDataProperty);
}
public static void SetPathData(DependencyObject obj, string value)
{
obj.SetValue(PathDataProperty, value);
}
public static readonly DependencyProperty PathDataProperty =
DependencyProperty.RegisterAttached("PathData", typeof(string), typeof(ElementExtensions), new PropertyMetadata(null, (d, e) =>
{
if (d is Path path)
{
Binding b = new Binding { Source = e.NewValue };
path.SetBinding(Path.DataProperty, b);
}
}));
And now you can define a style like so:
<Style x:Key="BasePathStyle" TargetType="Path">
<Setter Property="e:ElementExtensions.PathData" Value="M 10,100 C 10,300 300,-200 300,100" />
</Style>
And then use it like so:
<Path Style="{StaticResource BasePathStyle}" />
Given a style in a Page.Resource:
<Style x:Name="ItemTitle" TargetType="TextBlock">
<Setter Property="FontSize" Value="16"></Setter>
<Setter Property="FontWeight" Value="Bold"></Setter>
</Style>
It is correctly applied to any regular TextBlock on the same page.
However, when I use a DataTemplate for an Item in a GridView on that page, this style does not apply.
<DataTemplate x:Key="Output" x:DataType="vm:Output">
<TextBlock Text="{x:Bind Text}"></TextBlock>
</DataTemplate>
It does work when I apply the style explicitly on the DataTemplate, e.g.:
<DataTemplate x:Key="Output" x:DataType="vm:Output">
<TextBlock Style="{StaticResource ItemTitle}" Text="{x:Bind Text}"></TextBlock>
</DataTemplate>
Does anyone know what's up?
It's expected and intentional. If it doesn't derive from Control (like DataTemplate) then it won't inherit an implicit style unless they're in the application resource dictionaries as global defaults.
Or more specifically;
Templates are viewed as an encapsulation boundary when looking up an implicit style for an element which is not a subtype of Control.
Hope this helps. Cheers.
Addendum:
If it's a situation where you have a lot of the same element nested in a Template you can just set it once and allow it to inherit to all the nested controls of the type like (in pseudo);
<Parent>
<Parent.Resources>
<Style TargetType="TextBlock" BasedOn="{StaticResource ItemTitle}"/>
<Parent.Resources>
<!-- These will all inherit the Style resource now,
without explicit style setting individually. -->
<TextBlock/>
<TextBlock/>
<TextBlock/>
</Parent>
I would like to display some data on a ListView. The data is getting from a HttpClient request, but it's not so important at the moment. In the ListView I use Stackpanel and in this there are the datas. I would like to format the Stackpanel and the Textblocks inside the Stackpanel depending to their values. I can do it, but only in a complex way.
Here is my C# code:
public class TransTypeToAlignConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var ttype = (int)value;
HorizontalAlignment align;
switch (ttype)
{
case 1:
case 3:
align = HorizontalAlignment.Right;
break;
case 2:
align = HorizontalAlignment.Left;
break;
case 6:
align = HorizontalAlignment.Stretch;
break;
default:
align = HorizontalAlignment.Stretch;
break;
}
return align;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
And the XAML code:
<Page.Resources>
<local:TransTypeToAlignConverter x:Key="TransTypeToAlign" />
</Page.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ListView x:Name="myList" Height="Auto" Grid.Row="1">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="10,0,10,0">
<Rectangle Fill="DarkGray" Width="320" Margin="3,18,0,0" HorizontalAlignment="{Binding transactionType, Converter={StaticResource TransTypeToAlign}}"/>
<StackPanel Width="320" Margin="0,13,3,3" HorizontalAlignment="{Binding transactionType, Converter={StaticResource TransTypeToAlign}}" Background="Gray">
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
As I mentioned, this code is working. But I would like to format other things as well, not the Alignment only. For example I would like a dynamic Stackpanel width, not the fix 320px. For this I should write a code similar to the above. I think it's too much code for a similar thing, and it will be hard to modify later.
I have one value (TransType) which defines the alignment, the stackpanel width, the textblock message, and the color of the text. So, is it possible to make a template for formatting xaml?
A criticism of the pattern comes from MVVM creator John Gossman himself, who points out that the overhead in implementing MVVM is "overkill" for simple UI operations. MVVM Wiki
You can either do it with multiple converters or you can do it with a ItemTemplateSelector, in the latter case you would need to defined each template separately.
SO example of using ItemTemplateSelector
GridView ItemTemplateSelector
I have tried to set up combo boxes in the gridview but all the combo boxes have the same value in them instead of the value from the database. I am using entity framework and WPF. There is a parent child relationship between two tables but the source for the combo box is a separate table with names and IDs for tags. I have been looking all day. Hopefully this won't be too easy to solve.
The "Tag" Column displays the combo box. The Column "Tag ID" displays the value from the database. When I display the data the TagID Changes in diffrent rows but the Tag column is the same (the first choice) in all the rows. When I change one combo box they all change. I can't see where they are hooked together. Any assistance you can provide would be appreciated. (Buler?)
Here is the XAML
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="372" Width="675" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:my="clr-namespace:TagFinanceWPF">
<Window.Resources>
<CollectionViewSource x:Key="TransactionsViewSource" d:DesignSource="{d:DesignInstance my:Transaction, CreateList=True}" />
<CollectionViewSource x:Key="TransactionsTransactionTagsViewSource" Source="{Binding Path=TransactionTags, Source={StaticResource TransactionsViewSource}}" />
<CollectionViewSource x:Key="TagLookup" />
</Window.Resources>
<Grid DataContext="{StaticResource TransactionsViewSource}">
<ListView ItemsSource="{Binding Source={StaticResource TransactionsTransactionTagsViewSource}}" Margin="12" Name="TransactionTagsListView" SelectionMode="Single">
<ListView.ItemContainerStyle>
<Style>
<Setter Property="Control.HorizontalContentAlignment" Value="Stretch" />
<Setter Property="Control.VerticalContentAlignment" Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
<GridView>
<GridViewColumn x:Name="TransactionIDColumn1" Header="Transaction ID" Width="80">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Label Content="{Binding Path=TransactionID}" Margin="6,-1,-6,-1" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn x:Name="TagIDColumn" Header="Tag" Width="80">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ComboBox Margin="-6,-1"
ItemsSource="{Binding Source={StaticResource TagLookup}}"
DisplayMemberPath="TagName"
SelectedValuePath="TagID"
SelectedValue="{Binding TagID}"
IsReadOnly="True">
</ComboBox>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn x:Name="TagIDColumn2" Header="Tag ID" Width="80">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Label Content="{Binding Path=TagID}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Grid>
The VB code is:
Class MainWindow
Dim BentleyvideoEntities As TagFinanceWPF.bentleyvideoEntities = New TagFinanceWPF.bentleyvideoEntities()
Private Function GetTransactionsQuery(ByVal BentleyvideoEntities As TagFinanceWPF.bentleyvideoEntities) As System.Data.Objects.ObjectQuery(Of TagFinanceWPF.Transaction)
Dim TransactionsQuery As System.Data.Objects.ObjectQuery(Of TagFinanceWPF.Transaction) = BentleyvideoEntities.Transactions
'Update the query to include TransactionTags data in Transactions. You can modify this code as needed.
TransactionsQuery = TransactionsQuery.Include("TransactionTags")
'Returns an ObjectQuery.
Return TransactionsQuery
End Function
Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
'Load data into Transactions. You can modify this code as needed.
Dim TransactionsViewSource As System.Windows.Data.CollectionViewSource = CType(Me.FindResource("TransactionsViewSource"), System.Windows.Data.CollectionViewSource)
Dim TransactionsQuery As System.Data.Objects.ObjectQuery(Of TagFinanceWPF.Transaction) = Me.GetTransactionsQuery(BentleyvideoEntities)
TransactionsViewSource.Source = TransactionsQuery.Execute(System.Data.Objects.MergeOption.AppendOnly)
'Load data into Tags. You can modify this code as needed.
Dim customerList = From c In BentleyvideoEntities.Tags _
Order By c.TagName
Dim custSource = CType(Me.FindResource("TagLookup"), CollectionViewSource)
custSource.Source = customerList.ToList()
End Sub
End Class
I found this while researching your issue and it sounds like the exact same issue you are experiencing.
Snippit from link:
I'm not sure if this will help, but I
was reading in Chris Sells 'Windows
Forms Binding in C#, footnote, page
482', that the data source is bound to
each combobox and is managed by a
common Binding manager which in turn
is part of a Binding Context. The
Binding amager keeps all comboboxes
synchronized to the same row in the
database. However, if each combobox
has a different Binding context, hence
a diferent Binding Manager, then the
combo boxes can show different rows
from the same data source.
Based on this second article (and the suggested solution) you would need to use the row databinding event to set up the combobox's binding so that a new instace of the binding manager is created for each row bind.