Change visibility of a UWP button from code behind - c#

I have a "master frame" (which contains only the CommandBar) and some child frames, which are initially in a hub. Basically the frame changes, when one hub element is clicked on via "OnNavigated.."
Now I have some buttons (for example 1 and 2) which should not be visible, only when certain frames are chosen:
I've tried it with getter and setter methods:
In the Master-Frame code-methods:
public static Visibility setVisibility
{
set { Button1.Visibility = value; }
}
and in the Frame1 code behind:
MasterFrame.setVisibility = Visibility.Visible;
But I'm getting the error from Button1 "An object reference is...", because I have to use the "static" modifier to get access to the button from Frame1.
How can I get access to the button?
I don't even know if I'm using the "right" approach with the code-behind, but the MVVM seems to be not useful, as this isn't a CRUD-application (simple information without user-input.)

I don't even know if I'm using the "right" approach with the code-behind, but the MVVM seems to be not useful, as this isn't a CRUD-application (simple information without user-input.)
No, MVVM is useful, in the MVVM design pattern, developers can code app logic, and designers can create the UI. Although you're not developing a CRUD-application, MVVM pattern can still be used.
In a UWP app, Data Binding is very powerful. In this case, you can use data binding together with Converter to solve your problem.
I wrote a sample here to use Data Binding for event, and use Converter to judge the Visibility of Button and AppBarButtons:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.Resources>
<Converter:VisiableOrNot x:Key="cvt" />
<Converter:NaviButtonShowOrNot x:Key="btncvt" />
</Grid.Resources>
<CommandBar>
<CommandBar.Content>
<Grid>
<TextBlock Text="Master-Frame" FontSize="20" Margin="20,10" />
</Grid>
</CommandBar.Content>
<AppBarButton Icon="Accept" Label="appbarbutton" Visibility="{Binding ElementName=mainPageframe, Path=Content.BaseUri.AbsoluteUri, Converter={StaticResource cvt}}" />
<AppBarButton Icon="Cancel" Label="appbarbutton" Visibility="{Binding ElementName=mainPageframe, Path=Content.BaseUri.AbsoluteUri, Converter={StaticResource cvt}}" />
</CommandBar>
<Frame x:Name="mainPageframe" Margin="0,55">
<Hub x:Name="hub" SectionHeaderClick="{x:Bind MainPageViewModel.hub_SectionHeaderClick}">
<HubSection x:Name="image1" Header="Image1" Width="200" IsHeaderInteractive="True">
<DataTemplate>
<Grid>
<Image Source="Assets/111.png" Stretch="None" />
</Grid>
</DataTemplate>
</HubSection>
<HubSection x:Name="image2" Header="Image2" Width="200" IsHeaderInteractive="True">
<DataTemplate>
<Grid>
<Image Grid.Row="0" Source="Assets/222.png" Stretch="None" />
</Grid>
</DataTemplate>
</HubSection>
<HubSection x:Name="image3" Header="Image3" Width="200" IsHeaderInteractive="True">
<DataTemplate>
<Grid>
<Image Source="Assets/333.png" Stretch="None" />
</Grid>
</DataTemplate>
</HubSection>
</Hub>
</Frame>
<Button Content="Go Back" Click="{x:Bind MainPageViewModel.Button_Click}" Background="PaleGreen" VerticalAlignment="Bottom" Margin="50,20" Visibility="{Binding ElementName=mainPageframe, Path=Content.BaseUri.AbsoluteUri, Converter={StaticResource btncvt}}" />
</Grid>
Code of VisiableOrNot converter:
public class VisiableOrNot : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
Uri uri = new Uri(value.ToString());
if (uri != null)
{
if (uri.Equals("ms-appx:///View/Page3.xaml"))
{
return Visibility.Visible;
}
}
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
Here is the rendering image of my demo, the AppBarButtons can be seen only when the child frame's content is Page3. And the navigate back button can not be seen when it is on MainPage:
Here is my demo, you can download it and have a check.

To hide a ui element just do this:
this.MyComponent.Visibility = Visibility.Collapsed;
And to make it visible do this:
this.MyComponent.Visibility = Visibility.Visible;

Related

UWP App Randomly Crashes When Returning to Previous Page

I have an app where I list some items and then change to another page for editing. In the edit page, I have some fields where i need to choose a value from a list which I load in another page. I call the list page from the edit page, passing a method from the edit page view model to be invoked when a selection is made so that I can update my model and bindings.
The problem is that sometimes, when returning to the edit page, the debugger breaks in the generated file App.g.i.cs with an
"Error HRESULT E_FAIL has been returned from a call to a COM component." exception.
It fully displays the page with the correct bindings and selected values before breaking.
I've excluded possible errors from the async loading of the value list by replacing it with a dummy page and by removing any callbacks set by the edit page. The error still happened.
The edit page has its navigation cache mode set to Required so I don't lose the previous changes. I tried without a required cache mode and still got the error.
The only thing that seemed to resolve the issue was when I removed the bindings that used custom converters from the edit page xaml but I have those in other pages and never had a problem. (See Update)
The debugger break in the generated code:
#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
UnhandledException += (sender, e) =>
{
if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
};
This is the xaml for the edit page:
<Page.Resources>
<converters:BooleanToVisibilityConverter x:Key="BoolToVisibility" />
<converters:StringFormatConverter x:Key="StringFormat" />
<converters:DateTimeToDateTimeOffsetConverter x:Key="DateOffset" />
<converters:DateTimeToTimeSpanConverter x:Key="TimeSpan" />
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<fieldSelectControl:BackButtonAndTitle Title="Page Title" />
<StackPanel Grid.Row="1" Orientation="Horizontal">
<Button Name="HomeButton"
Width="70"
Height="50"
Background="Black"
Content=""
FontFamily="Segoe MDL2 Assets"
FontSize="30" />
<TextBlock Name="PageTitle"
FontSize="36"
Text="{Binding OrderTitle}" />
</StackPanel>
<ProgressRing Grid.Row="2" IsActive="{Binding IsLoading}" />
<ScrollViewer Grid.Row="2"
Height="Auto"
HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Auto"
Visibility="{Binding Path=FinishedLoading,
Converter={StaticResource BoolToVisibility}}">
<StackPanel Margin="20,10,20,30">
<TextBlock Margin="0,5,0,5"
Style="{StaticResource DetailLabel}"
Text="Date" />
<DatePicker Date="{Binding Day, Mode=TwoWay, Converter={StaticResource DateOffset}}" />
<TextBlock Margin="0,15,0,5"
Style="{StaticResource DetailLabel}"
Text="Type" />
<ComboBox ItemsSource="{Binding ComboValues}" SelectedItem="{Binding SelectedHourType, Mode=TwoWay}" />
<TextBlock Margin="0,15,0,5"
Style="{StaticResource DetailLabel}"
Text="Start" />
<TimePicker ClockIdentifier="24HourClock" Time="{Binding StartTime, Mode=TwoWay, Converter={StaticResource TimeSpan}}" />
<TextBlock Margin="0,5,0,5"
Style="{StaticResource DetailLabel}"
Text="End" />
<TimePicker ClockIdentifier="24HourClock" Time="{Binding EndTime, Mode=TwoWay, Converter={StaticResource TimeSpan}}" />
<TextBlock Margin="0,15,0,5"
Style="{StaticResource DetailLabel}"
Text="Amount" />
<TextBox InputScope="Number" Text="{Binding HValue, Mode=TwoWay}" />
<fieldSelectControl:FieldWithIconSelector x:Name="fsSelect"
IconClickedEvent="btnClose_Click"
IconField=""
TitleField="Add..."
TitleIconField=""
ValueField="" />
<ScrollViewer Height="Auto"
HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Auto">
<ListView x:Name="lstOrders"
Height="auto"
MaxHeight="600"
HorizontalAlignment="Stretch"
IsItemClickEnabled="True"
ItemClick="lstOrders_ItemClick"
ItemsSource="{Binding SelectedEmployees,
Mode=OneWay}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="data:Responsible">
<fieldSelectControl:FieldWithIconSelector x:Name="fsEmployees"
IconClickedEvent="fsEmployees_IconClickedEvent"
IconField=""
TitleField=""
TitleIconField=""
ValueField="{Binding Name}" />
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>
</ListView>
</ScrollViewer>
<Button Name="btnSave"
Margin="0,20,0,15"
HorizontalAlignment="Stretch"
Click="btnSave_Click"
Visibility="{Binding Path=FinishedSaving,
Converter={StaticResource BoolToVisibility}}">
<Button.Template>
<ControlTemplate>
<StackPanel HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Background="#0099cc"
Orientation="Vertical"
Padding="5">
<TextBlock HorizontalAlignment="Center"
FontFamily="Segoe MDL2 Assets"
FontSize="25"
Text="" />
<TextBlock HorizontalAlignment="Center" Text="Save" />
</StackPanel>
</ControlTemplate>
</Button.Template>
</Button>
</StackPanel>
</ScrollViewer>
</Grid>
Code for the DateOffset Converter:
public class DateTimeToDateTimeOffsetConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
try
{
if (value is DateTime)
{
DateTime date = (DateTime)value;
return new DateTimeOffset(date);
}
else
return new DateTimeOffset(DateTime.Now);
}
catch (Exception ex)
{
return new DateTimeOffset(DateTime.Now);
}
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
DateTimeOffset dto = (DateTimeOffset)value;
return dto.DateTime;
}
}
Code for the TimeOffset Converter:
public class DateTimeToTimeSpanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
try
{
if (value is DateTime)
{
DateTime date = (DateTime)value;
return new TimeSpan(date.Ticks);
}
else
return new TimeSpan(DateTime.Now.Ticks);
}
catch (Exception ex)
{
return new TimeSpan(DateTime.Now.Ticks);
}
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
TimeSpan ts = (TimeSpan)value;
DateTime dt = new DateTime(ts.Ticks);
return dt;
}
}
Given the code where the debugger breaks, the error seems to be on the xaml side and, as I said, removing the date and time pickers, which are the only elements where the binding uses a custom converter, seems to fix it.
What am I missing?
UPDATE
Further testing has brought to my attention that removing the custom converters doesnt actually fix the issue, it just increases the number of navigations until the error happens. I've tried removing the bindings altogether and still got the error. Removing every element but the button that calls the next page seems to work but at this point I can't tell for sure if it actually fixes the issue or just mitigates it.
On a side note, navigating back to the first page using the phone Back button works flawlessly. The error only seems to happen if Frame.GoBack() is explicitly invoked.
These sorts of exceptions don't provide too many hints as to what's causing them, but there are a few things you could try:
I'd remove the ScrollViewer from around lstOrders. It doesn't add any value, yet it could break virtualization of the ListView causing it to try to use arbitrary amounts of memory and CPU if you'd accidentally removed MaxHeight set on the lstOrders.
The btnSave template is bad as it removes interactive feedback elements.
Make sure the properties you bind to are not changed off the UI/Dispatcher thread.
As mentioned in the comments on the question, I have been experiencing this issue today. It was relatively straight forward to isolate the issue to the TimePicker control and, more specifically, the two way binding on the Time property of the control.
However, it was less straight forward to work out why it was happening. It seems to be some issue around visibility (I experience the issue when moving my app to the background) and updating the bound value. Regardless, I tried a variety of things to no avail.
In the end, I tried changing the binding expression from the traditional {Binding} syntax to the compiled {x:Bind} and, fortunately, the problem went away.
Perhaps, give that a shot and see if it solves your problem. Obviously the TimePicker will need to be inside a DataTemplate with a data type specific or - as in my case - a user control with custom dependency properties.

Handle Event inside bound ListBox

I'm struggling to solve this problem, i'm trying to handle the PreviewMouseLeftButtonDown & MouseEnter & MouseLeave event inside my bound ListBox. Currently learning WPF.
The Image is inside my ListBox with other Controls here's a Picture for clarification.
My Problem is the two Image Controls are not known in Code behind because they are inside a DataTemplate and thats why i cant handle them.
Heres my Xaml Code:
<ListBox Name="ListBoxDownload" Height="414" Width="729" Canvas.Left="-3" Visibility="Collapsed">
<ListBox.ItemTemplate>
<DataTemplate>
<Canvas Height="89" >
<Canvas Height="86" Width="11" Background="#FFC33232" Canvas.Left="-2"/>
<ProgressBar Width="694" Canvas.Left="20" Canvas.Top="76" Height="10" Value="{Binding Value, UpdateSourceTrigger=PropertyChanged}" Maximum="{Binding Maximum}" Minimum="0"/>
<Label Foreground="White" FontFamily="/SpotWatch;component/Resources/Fonts/#Montserrat Light" FontSize="18" Content="{Binding Name}" Canvas.Left="14" Canvas.Top="-4"/>
<Label Foreground="#FFC3BDBD" FontFamily="/SpotWatch;component/Resources/Fonts/#Montserrat Ultra Light" FontSize="14" Content="{Binding Artist}" Canvas.Left="14" Canvas.Top="25"/>
<Label Foreground="#FF8D8D8D" FontFamily="/SpotWatch;component/Resources/Fonts/#Montserrat Ultra Light" FontSize="12" Content="{Binding Status}" Canvas.Left="14" Canvas.Top="50"/>
<Image Name="ImageDeleteSong" Source="/Resources/Images/SpotWatch.Delete.png" Canvas.Left="675" Canvas.Top="6" Width="17" Height="19" MouseEnter="ImageDeleteSong_MouseEnter" MouseLeave="ImageDeleteSong_MouseLeave" PreviewMouseLeftButtonDown="ImageDeleteSong_PreviewMouseLeftButtonDown"/>
<Image Name="ImageRemoveSong" Source="/Resources/Images/SpotWatch.Remove.png" Canvas.Left="697" Canvas.Top="6" Width="17" Height="19" MouseEnter="ImageRemoveSong_MouseEnter" MouseLeave="ImageRemoveSong_MouseLeave" PreviewMouseLeftButtonDown="ImageRemoveSong_PreviewMouseLeftButtonDown"/>
</Canvas>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The images do not need to be known in code behind, if you hook up the events you get the image control passed as the first argument. You just need to cast it.
Alternatively wrap the images in a button, bind the Command and pass something via the CommandParameter binding as needed. (Usually i avoid events and bind commands on view-models instead.)
Why do you need to access the images anyway? That's not something you should need to do. If you need to modify them you should bind the respective properties and then modify your bound data instead.
Given what you said in the comments, this is what i would do:
public SomeViewModel()
{
_deleteUser = new DelegateCommand(user =>
Users.Remove((Person)user)
);
}
private readonly ObservableCollection<Person> _Users;
public ObservableCollection<Person> Users { get { return _Users; } }
private readonly DelegateCommand _deleteUser;
public DelegateCommand DeleteUser { get { return _deleteUser; } }
<ItemsControl ItemsSource="{Binding Users}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<!-- Some content here -->
<Button Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl},
Path=DataContext.DeleteUser}"
CommandParameter="{Binding}">Remove</Button>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Key points:
Delete command at level of list.
Button binds to it via RelativeSource
Passes current item ({Binding}) as parameter.
Command casts parameter and removes it from list.
(DelegateCommand is a simple delegate based implementation of ICommand, you can find implementation examples on the web.)

Set automatic visible or collapse on TextBlock in LongListPicker item

I have LongListPicker with custom DataTemplate. In that DataTemplate I have TextBlock and text is bind to SubItemNames. I have also property SubItemsVisible which is Boolean, and I would like to collapde TextBlock when HasSubItemNames is false.
I've created Converter:
public class BoolVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (bool)value ? Visibility.Visible : Visibility.Collapsed;
}
}
and add to my XAML:
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Key="StateItemTemplate">
<StackPanel VerticalAlignment="Top">
<TextBlock Text="{Binding ItemName}" Foreground="#DE000000" FontFamily="Segoe WP SemiLight" FontSize="24" />
<Path Data="M-65,106 L169.77,106" Fill="#FF0A0AE4" Height="3" Stretch="Fill" Stroke="Black" UseLayoutRounding="False"/>
<TextBlock Text="{Binding SubItemNames}" Visibility="{ Binding SubItemsVisible , Converter={StaticResource BoolVisibilityConverter}}" Foreground="#DE636363" FontFamily="Segoe WP SemiLight" FontSize="16" />
<Path Data="M-65,106 L169.77,106" Fill="#FF0A0AE4" Height="3" Stretch="Fill" Stroke="Black" UseLayoutRounding="False"/>
</StackPanel>
</DataTemplate>
but still I am missing something, because I've got error: The resource "BoolVisibilityConverter" could not be resolved. What should I add to my XAML page?
You need to create the static resource called BoolVisibilityConverter to referrence it
You can create it in App.xaml to be globally visible or in your Page Resources section
First, add xmlns statement:
xmlns:converters="clr-namespace:ConverterNamespace"
App.xaml declaration example:
<Application.Resources>
<ResourceDictionary>
<converters:BoolVisibilityConverter x:Key="BoolVisibilityConverter" />
</ResourceDictionary>
</Application.Resources>
Page.xaml declaration example:
<phone:PhoneApplicationPage.Resources>
<converters:BoolVisibilityConverter x:Key="BoolVisibilityConverter" />
</phone:PhoneApplicationPage.Resources>

show image in tabcontrol tab header if textbox has text WPF

Okay, What I'm trying to accomplish:
A tabheader which gets an image if the textbox inside has text. but if the textbox inside the TabItem doesn't have any text, then the image should not be shown.
this is what I have so far:
----- TAB ITEM CODE -----
<TabItem Name="tabAantekeningen" Header="">
<TabItem.HeaderTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Margin="8" Text="Aantekeningen"/>
<Image Grid.Column="1" Source="..\Resources\validate.png" Height="20" Width="17"/>
</Grid>
</DataTemplate>
</TabItem.HeaderTemplate>
<TextBox Name="txtOmschrijving" TextWrapping="Wrap" AcceptsReturn="True"></TextBox>
</TabItem>
----- TAB ITEM CODE -----
----- Code Behind -----
public void SetTabItemHeader()
{
if (String.IsNullOrEmpty(txtOmschrijving.Text))
{
tabAantekeningen.Header = "Aantekeningen";
}
}
----- Code Behind -----
IS there a way that I can say: txtOmschrijving.Text == Empty so hide the Image?
Edit: Didn't see your seccond question there, yes there is use a IValueConverter, where you check if the string is empty and Bind To Visibility for instance, so you return Visbility.Collapsed when empty or else Visbility.Visible.
Like this :
public class StringEmptyToVisbililityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (value == null) || !(value is string) || string.IsNullOrEmpty(value.ToString()) ? Visibility.Collapsed : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Fully working xaml, change your namespaces and URI pack
<Window x:Class="TabItemHeader.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TabItemHeader"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:StringEmptyToVisbililityConverter x:Key="StringEmptyToVisbililityConverter"/>
</Window.Resources>
<Grid>
<TabControl>
<TabItem Name="tabAantekeningen">
<TabItem.HeaderTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Margin="8" Text="{Binding Path='Header',RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type TabItem}}}"/>
<Image Grid.Column="1" Source="pack://application:,,,/TabItemHeader;component/Resources/Images/validate.png" Height="20" Width="17" Visibility="{Binding Path='Header', Converter={StaticResource StringEmptyToVisbililityConverter}, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type TabItem}}}"/>
</Grid>
</DataTemplate>
</TabItem.HeaderTemplate>
<TextBox Name="txtOmschrijving" TextWrapping="Wrap" AcceptsReturn="True"></TextBox>
</TabItem>
</TabControl>
</Grid>
This will bind to the listboxitem which wraps everything in a listbox. The converter will only show this image when the string is not empty. You can do alot of fun with them :)
WPF cheat sheet is a really handy and compact paper on all types of bindings.
Oh..I am assuming this image will be deployed with your application? Then please ensure that your image is set to resource, you should consider using uri packs as well for your images, an example is in this post as well as the xaml provided. If your image is dynamic, you will have to bind them to some model in an observablecollection.
Tip: I'll stop pushing this to far, but you should consider having a look at the MVVM pattern. I just used code behind my self, so the answer wouldn't get to big. It's whole other topic! =) There are also cleaner ways to either share templates, and change them on types bound in the collection.
Hope it helps.
Cheers,
Stian

ValueConverter doesn't work in FlipView

I have a ListView in a FlipView
<FlipView
x:Name="flipView"
AutomationProperties.AutomationId="ItemsFlipView"
AutomationProperties.Name="Item Details"
TabIndex="1"
Width="Auto"
Grid.Row="2"
Grid.Column="1"
VerticalAlignment="Top"
HorizontalAlignment="Center"
ItemsSource="{Binding Source={StaticResource itemsViewSource}}" Padding="0" VirtualizingStackPanel.VirtualizationMode="Standard">
<FlipView.ItemTemplate>
<DataTemplate>
<!--
UserControl chosen as the templated item because it supports visual state management
Loaded/unloaded events explicitly subscribe to view state updates from the page
-->
<UserControl Loaded="StartLayoutUpdates" Unloaded="StopLayoutUpdates">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="1" Orientation="Vertical" Margin="0,100,0,0">
<ListView x:Name="ListofOptions" Height="400" Width="280"
ItemsSource="{Binding QuestionOptions}" SelectedValue="{Binding Answer,Mode=TwoWay}"
IsEnabled="{Binding IsEnabled,Mode=TwoWay}" >
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<StackPanel.Resources>
<common:AltBackgroundConverter x:Key="BGConvertor" />
</StackPanel.Resources>
<StackPanel.Background>
<SolidColorBrush Color="{Binding IndexWithinParentCollection, Mode=OneWay, Converter={StaticResource BGConvertor}}"></SolidColorBrush>
</StackPanel.Background>
<TextBlock Text="{Binding OptionValue}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
</Grid>
</UserControl>
</DataTemplate>
</FlipView.ItemTemplate>
</FlipView>
I write a value conventor of ListView for changing background of alternative row. here is Conventor's code
public class AltBackgroundConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (!(value is int)) return null;
int index = (int)value;
if (index % 2 == 0)
return Colors.White;
else
return Colors.LightGray;
}
// No need to implement converting back on a one-way binding
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
when the listbox is out of FlipView everything is Ok but the Conventor doesn't execute when the ListView is in a FlipView. please advice me.
Created a new Split XAML project in VS2012 and added your converter there and used it in ListView and it was still working after moving the ListView inside a FlipView.
I'm now guessing it's a binding issue, happening because root binding object has changed and one of the bindings not resolved as we expect. have you tried moving the Resources tag to upper level which is the FlipeView?
P.S. This is more of a comment, but I don't have reputation for comments!

Categories

Resources