I create a templated RadioButton at run time. After initializing the templated RadioButton, I set the DataContext and Tag property and then add this button in a StackPanel. The problem is that the template binding does not work. below is the XAML and the code behind. All this work if I assign values to these properties in XAML. Any ideas?
Code:
TemplatedRadioButton commandButton = new TemplatedRadioButton();
commandButton.DataContext = "bla"; // Some txt that I will.
commandButton.Tag = MyImage; // This is the ImageIcon that I create at run time too.
MyStackPanel.Children.Add(commandButton);
XAML:
Sorry:
Code:
TemplatedRadioButton commandButton = new TemplatedRadioButton();
commandButton.DataContext = "bla"; // Some txt that I will.
commandButton.Tag = MyImage; // This is the ImageIcon that I create at run time too.
MyStackPanel.Children.Add(commandButton);
XAML:
<Grid Margin="0 8 0 1">
<Grid.RowDefinitions>
<RowDefinition Height="4*"/>
<RowDefinition Name="textheight" Height="2*"/>
</Grid.RowDefinitions>
<ContentPresenter x:Name="Content" ContentSource="Tag" Margin=" 4 4 6 6" HorizontalAlignment="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{Binding VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
<TextBlock Name="caption" Text="{TemplateBinding DataContext}" FontSize="11" FontFamily="/Fonts/#Lucida Grande" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Bottom" Foreground="#FF313131" Margin="0 2 0 6"/>
</Grid>
</Border>
Related
I've see this topic a few times but right now when I need it, I can't find it... I have a problem with a few ListView's in my app. The ListViews are displaying content from a database and from a webservice. The content of the ListView can be very large and sometimes, the text is cut off...
This is my ListView so far:
<ListView Grid.Row="1" x:Name="DataListView" ItemsSource="{Binding GroupData}" GroupShortNameBinding="{Binding ShortCategory}" CachingStrategy="RecycleElement"
IsGroupingEnabled="True" HasUnevenRows="True" BackgroundColor="#b99f65" SeparatorColor="#55492e" ItemTapped="ListView_OnItemTapped" Margin="0,3,0,0">
<ListView.GroupHeaderTemplate>
<DataTemplate>
<ViewCell>
<Grid BackgroundColor="#120305" Margin="0">
<StackLayout Orientation="Horizontal" VerticalOptions="Center" Margin="15,0">
<Label Text="{Binding Category}" TextColor="#b99f65" FontSize="18" FontAttributes="Bold" />
<Label Text="{Binding ShortCategory, StringFormat='({0})'}" FontSize="18" TextColor="#b99f65" />
</StackLayout>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.GroupHeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Vertical" Margin="10,5" VerticalOptions="Fill">
<Label Text="{Binding Name}" FontSize="14" FontAttributes="Bold" Margin="0" />
<Label Text="{Binding Effect}" FontSize="11" LineBreakMode="WordWrap" Margin="0" />
<Label Text="{Binding Ingredients, StringFormat='Ingredients: {0}'}" FontSize="11" LineBreakMode="WordWrap" Margin="0,3,0,0" SizeChanged="OnLabelSizeChanged" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Here, the Ingredients are cut off in iOS on some device sizes. I have implemented a SizeChanged-Event for the last Label to see if the size is set correctly, and it is. This is the output:
[0:] LABEL HEIGHT CHANGED:: 26.5
[0:] LABEL HEIGHT CHANGED:: 26.5
[0:] LABEL HEIGHT CHANGED:: 13.5
[0:] LABEL HEIGHT CHANGED:: 13.5
[0:] LABEL HEIGHT CHANGED:: 26.5
[0:] LABEL HEIGHT CHANGED:: 13.5
[0:] LABEL HEIGHT CHANGED:: 26.5
[0:] LABEL HEIGHT CHANGED:: 13.5
[0:] LABEL HEIGHT CHANGED:: 26.5
[0:] LABEL HEIGHT CHANGED:: 13.5
Any of the "26.5" height labels are cut off in half. Because this only happens on iOS it must be a problem there. Can someone help me out to fix this? I have the same issue on other places of my App too and haven't found a working solution yet... I know I can set the RowHeight to the max possible value but for this I need to know how many times the text will be wraped and it is not a nice solution... I would like to use the dynamic sizing...
As a workaround I currently use this on the last Label in iOS, but it takes a huge amount of performance and looks very bad...
private void OnLabelSizeChanged(object sender, EventArgs e)
{
var stackLayout = (sender as Label)?.Parent as StackLayout;
if (stackLayout != null)
{
var childrenHeight = stackLayout.Children.Sum(c => c.Height) + stackLayout.Children.Count * stackLayout.Spacing;
stackLayout.HeightRequest = childrenHeight;
var viewCell = stackLayout.Parent as ViewCell;
viewCell?.ForceUpdateSize();
}
}
And beside of the performance lost it also makes the app looks wrong if the device orientation changes.
I've got a Windows Store app with a RichEditBox (editor) and a Grid (MarginNotes).
I need the vertical scroll position of the two elements to be matched at all times. The purpose of this is to allow the user to add notes in the margin of the document.
I've already figured out Note positioning based on the cursor position - when a note is added, a text selection is made of everything up to the cursor. that selection is then added to a second, invisible RichEditBox, inside a StackPanel. I then get the ActualHeight of this control which gives me the position of the note in the grid.
My issue is that when I scroll the RichEditBox up and down, the Grid does not scroll accordingly.
First Technique
I tried putting them both inside a ScrollViewer, and disabling scrolling on the RichEditBox
<ScrollViewer x:Name="EditorScroller"
VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150" />
<ColumnDefinition Width="{Binding *" />
<ColumnDefinition Width="150" />
</Grid.ColumnDefinitions>
<Grid x:Name="MarginNotes" Grid.Column="0" HorizontalAlignment="Right"
Height="{Binding ActualHeight, ElementName=editor}">
</Grid>
<StackPanel Grid.Column="1">
<RichEditBox x:Name="margin_helper" Opacity="0" Height="Auto"></RichEditBox>
</StackPanel>
<RichEditBox x:Name="editor" Grid.Column="1" Height="Auto"
ScrollViewer.VerticalScrollBarVisibility="Hidden" />
</Grid>
</ScrollViewer>
When I scroll to the bottom of the RichEditBox control, and hit enter a few times, the cursor drops out of sight. The ScrollViewer doesn't scroll automatically with the cursor.
I tried adding C# code which would check the position of the cursor, compare it to the VerticalOffset and height of the editor, and then adjust the scroll accordingly. This worked, but was incredibly slow. Initially I had it on the KeyUp event which brought the app to a standstill when I typed a sentence. Afterwards I put it on a 5 second timer, but this still slowed down the app performance and also meant that there could be a 5 second delay between the cursor dropping out of sight and the RichEditBox scrolling.
Second Technique
I also tried putting just MarginNotes in its own ScrollViewer, and programmatically setting the VerticalOffset based off my RichEditBoxs ViewChanged event.
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150" />
<ColumnDefinition Width="{Binding *" />
<ColumnDefinition Width="150" />
</Grid.ColumnDefinitions>
<ScrollViewer x:Name="MarginScroller" Grid.Column="0"
VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<Grid x:Name="MarginNotes" HorizontalAlignment="Right"
Height="{Binding ActualHeight, ElementName=editor}">
</Grid>
</ScrollViewer>
<StackPanel Grid.Column="1">
<RichEditBox x:Name="margin_helper" Opacity="0" Height="Auto"></RichEditBox>
</StackPanel>
<RichEditBox x:Name="editor" Grid.Column="1" Height="Auto"
Loaded="editor_loaded" SizeChanged="editor_SizeChanged" />
</Grid>
relevant event handlers
void editor_Loaded(object sender, RoutedEventArgs e)
{
// setting this in the OnNavigatedTo causes a crash, has to be set here.
// this uses WinRTXAMLToolkit as suggested by Nate Diamond to find the
// ScrollViewer and add the event handler
editor.GetFirstDescendantOfType<ScrollViewer>().ViewChanged += editor_ViewChanged;
}
private void editor_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
{
// when the RichEditBox scrolls, scroll the MarginScroller the same amount
double editor_vertical_offset = ((ScrollViewer)sender).VerticalOffset;
MarginScroller.ChangeView(0, editor_vertical_offset, 1);
}
private void editor_SizeChanged(object sender, SizeChangedEventArgs e)
{
// when the RichEditBox size changes, change the size of MarginNotes to match
string text = "";
editor.Document.GetText(TextGetOptions.None, out text);
margin_helper.Document.SetText(TextSetOptions.None, text);
MarginNotes.Height = margin_helper.ActualHeight;
}
This worked, but was quite laggy as scrolling is not applied until the ViewChanged event fires, after scrolling has stopped. I tried using the ViewChanging event, but it does not fire at all for some reason. Additionally, the Grid was sometimes mis-positioned after a fast scroll.
So, what makes this difficult is that the size of the text or the placement of the text in different types of TextBoxes means that syncing the scrollbar doesn't guarantee you are syncing the text. Having said that, here's how you do it.
void MainPage_Loaded(object sender, RoutedEventArgs args)
{
MyRichEditBox.Document.SetText(Windows.UI.Text.TextSetOptions.None, MyTextBox.Text);
var textboxScroll = Children(MyTextBox).First(x => x is ScrollViewer) as ScrollViewer;
textboxScroll.ViewChanged += (s, e) => Sync(MyTextBox, MyRichEditBox);
}
public void Sync(TextBox textbox, RichEditBox richbox)
{
var textboxScroll = Children(textbox).First(x => x is ScrollViewer) as ScrollViewer;
var richboxScroll = Children(richbox).First(x => x is ScrollViewer) as ScrollViewer;
richboxScroll.ChangeView(null, textboxScroll.VerticalOffset, null);
}
public static IEnumerable<FrameworkElement> Children(FrameworkElement element)
{
Func<DependencyObject, List<FrameworkElement>> recurseChildren = null;
recurseChildren = (parent) =>
{
var list = new List<FrameworkElement>();
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is FrameworkElement)
list.Add(child as FrameworkElement);
list.AddRange(recurseChildren(child));
}
return list;
};
var children = recurseChildren(element);
return children;
}
Deciding when to invoke the sync is tricky. Maybe on PointerReleased, PointerExit, LostFocus, KeyUp - there are a lot of ways to scroll is the real issue there. You might need to handle all of those. But, it is what it is. At least you can.
Best of luck.
I'm starting developing app in WindowsPhone, and had some problems. I trying to add a canvas dynamically, but it does not work, I may forgot about something, could you help to spot my error? Code below is from my learning app, it is basic Win Phone app.
cs code:
public MainPage()
{
InitializeComponent();
int size = 50;
Canvas myCanvas = new Canvas();
Canvas.SetLeft(myCanvas, 0);
myCanvas.Width = size;
Color c = new Color();
c.R = 255;
c.B = 0;
c.G = 255;
myCanvas.Background = new SolidColorBrush(c);
ContentPanel.Height = 100;
ContentPanel.Width = 100;
ContentPanel.Children.Add(myCanvas);
ApplicationTitle.Text = ContentPanel.ActualHeight.ToString();
}
xaml
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
</Grid>
</Grid>
I'm not quite sure what you're trying to accomplish here with the Canvas. You may want to look into other controls to get what you're trying to do.
That being said, the problem is that you are missing your "Alpha" component in the color. This is making it transparent.
Change:
Color c = new Color();
c.R = 255;
c.B = 0;
c.G = 255;
c.A = 255; // this is what you need to add to make it visible.
I'm attempting to databind a gradient brush as a Rectangle fill. What do I need to do to get the commented-out binding to work? StartColor and EndColor are declared as System.Drawing.Color.
<Rectangle Width="100" Height="20">
<Rectangle.Fill>
<LinearGradientBrush>
<GradientStop Offset="0" Color="Pink"/>
<GradientStop Offset="1" Color="Red"/>
<!--<GradientStop Offset="0" Color="{Binding Path=StartColor}"/>-->
<!--<GradientStop Offset="1" Color="{Binding Path=EndColor}" />-->
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
The problem was using System.Drawing.Color rather than the proper System.Windows.Media.Color
Is there a way to set the Default Layout Orientation when printing XPSs using the WPF XPS Viewer?
My fixed document XPS has its page orientation set to Landscape, the Page Media Size has a width that is longer that its height and it displays correctly in the Viewer as Landscape.
Its just that when you hit the print button the Print Dialog preferences are defaulted to Portrait and it prints as such.
I'd rather not have to alter the users default print settings I'd much prefer it if the XPS Viewer would print the XPS as it was designed to be printed.
Fill the field of the PrintTicket:
PrintDialog pd = new PrintDialog();
PrintTicket pt = new PrintTicket();
pt.PageOrientation = PageOrientation.Landscape;
pd.PrintTicket = pd.PrintQueue.MergeAndValidatePrintTicket(pd.PrintQueue.DefaultPrintTicket, pt).ValidatedPrintTicket;
if (pd.ShowDialog() == true)
{
...
}
I believe the correct way to do this when creating a FixedDocument, is set the RenderTransform = RotateTransform(90) on the page content when the dimensions are higher than they are wide.
Example:
var visualContent = new Image
{
Source = image,
Stretch = Stretch.Uniform
};
visualContent.RenderTransformOrigin = new Point(0.5, 0.5);
visualContent.RenderTransform = new RotateTransform(90);
FixedPage fixedPage = new FixedPage();
fixedPage.Children.Add(visualContent);
var pageContent = new PageContent
{
Child = fixedPage
};
Not sure if that helps with a pre-existing XPS document however.
This is not really a problem with MXDW but one with the way drivers work on Windows. The user choice(s) is/are saved for a particular session. This means that you can reuse firs-print settings when printing between the first print and quitting the application. Most printers behave this way, until unless one comes up with a way to save this information somewhere and let the user re-use it across sessions.
So, I tried hacking the GPD file (where printing information for a printer is typically stored). The orientation has two possible values: PORTRAIT and LANDSCAPE_CC270 with the default being set to PORTRAIT. See below:
*%******************************************************************************
*% Orientation
*%******************************************************************************
*Feature: Orientation
{
*rcNameID: =ORIENTATION_DISPLAY
*DefaultOption: PORTRAIT
*Option: PORTRAIT
{
*rcNameID: =PORTRAIT_DISPLAY
}
*Option: LANDSCAPE_CC270
{
*rcNameID: =LANDSCAPE_DISPLAY
}
}
Now, if I were to change swap the default value to LANDSCAPE_CC270, the printing preferences stop coming up (and any print would fail). In fact, it appears, that specifying any other value keeps the default to PORTRAIT. Definitely, MS is
doing some sort of check to prevent us from hacking this driver. Looks like MS doesn't
want anyone to tamper with its settings :(
But you could try flirting with the GPD values a bit more and see if something of your liking comes up. Will keep hacking a bit more.
Caveat: GPD files shouldn't be tampered with if you don't know what you are doing. If you
still want to go ahead make a backup!
Hint: They are stored in %WINDOWS%system32\spool\drivers\w32x86\3 folder.
<Grid Margin="0,0,-8,-8">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<FlowDocumentScrollViewer Name="printpanel" HorizontalAlignment="Left" Width="959" FontFamily="Arial" Margin="0,-10,0,10">
<FlowDocument x:Name="FD">
<BlockUIContainer>
<Canvas>
<Label x:Name="lblReceipt" Visibility="Visible" Content="Receipt No." HorizontalAlignment="Left" VerticalAlignment="Top" Canvas.Top="178" FontSize="12" Canvas.Left="60"/>
<Label x:Name="txtReceiptNo" BorderThickness="2" BorderBrush="Black" HorizontalAlignment="Left" Padding="10,3,3,0" Height="23" VerticalAlignment="Top" Width="200" FontSize="12" Canvas.Left="187" Canvas.Top="177" FontFamily="Arial"/>
<Label x:Name="lblmemNo" Visibility="Visible" Content="Membership No." HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="12" Canvas.Left="462" Canvas.Top="177"/>
<Label x:Name="txtMembershipNo" BorderThickness="2" BorderBrush="Black" HorizontalAlignment="Left" Padding="10,3,3,0" Height="23" VerticalAlignment="Top" Width="177" FontSize="12" Canvas.Left="604" Canvas.Top="177" FontFamily="Arial">
</Label>
<Label x:Name="lblAuthCentr" Visibility="Visible" Content="Authorised Center." HorizontalAlignment="Left" VerticalAlignment="Top" Canvas.Left="60" Canvas.Top="221" FontSize="12"/>
<TextBox x:Name="txtAuthCentr" HorizontalAlignment="Left" TextWrapping="WrapWithOverflow" Padding="10,3,3,0" Height="38" VerticalAlignment="Top" Width="219" FontSize="12" Canvas.Left="238" Canvas.Top="219" FontFamily="Arial"/>
<Label x:Name="lblSector" Visibility="Visible" Content="Sector." HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="12" Canvas.Left="492" Canvas.Top="220"/>
<Label x:Name="txtSector" BorderThickness="2" BorderBrush="Black" HorizontalAlignment="Left" Padding="10,3,3,0" Height="23" VerticalAlignment="Top" Width="115" FontSize="12" Canvas.Left="567" Canvas.Top="220" FontFamily="Arial"/>
</Canvas>
</BlockUIContainer>
</FlowDocument>
</FlowDocumentScrollViewer>
<Button Name="btnOk" Content="Print" Height="30" Grid.Row="1" Click="btnOk_Click" Margin="355,0,404,0"></Button>
</Grid>
Just set FlowDocument Height and width
set FD.PageWidth = 1100; FD.PageHeight = 600;
private void btnOk_Click(object sender, RoutedEventArgs e)
{
if (File.Exists("printPreview.xps"))
{
File.Delete("printPreview.xps");
}
var xpsDocument = new XpsDocument("printPreview.xps", FileAccess.ReadWrite);
XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
DocumentPaginator docPage;
FD.PageWidth = 1100; // set FlowDocument Width
FD.PageHeight = 600; // set FlowDocument Height
docPage = ((IDocumentPaginatorSource)FD).DocumentPaginator;
writer.Write(docPage);
Document = xpsDocument.GetFixedDocumentSequence();
this.Close();
xpsDocument.Close();
var windows = new PrintWindow(Document);
windows.ShowDialog();
}