Creating Canvas dynamically - windows-phone-7.1

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.

Related

.NET MAUI: Unwanted whitespace at bottom of screen using grid layout

I have a simple grid layout:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="5*" />
<RowDefinition Height="1*" />
</Grid.RowDefinitions>
<Button Grid.Row="0"
Text="Test1"
VerticalOptions="Fill"
BackgroundColor="Green"/>
<Button Grid.Row="1"
Text="Test2"
VerticalOptions="Fill"
BackgroundColor="Red"/>
</Grid>
I expect the red area to extend all the way to the bottom of the screen. However, There's some white space.
If I change it to a collection view with a footer, it properly fills the bottom section of the screen:
For reference:
<CollectionView>
<CollectionView.Header>
<Button
Text="Test1"
VerticalOptions="Fill"
BackgroundColor="Green"/>
</CollectionView.Header>
<CollectionView.EmptyView>
<Label Text="No items"/>
</CollectionView.EmptyView>
<CollectionView.Footer>
<Button
Text="Test2"
VerticalOptions="Fill"
BackgroundColor="Red"/>
</CollectionView.Footer>
</CollectionView>
Is there a correct way to fill that bottom "footer" area on a grid view? or without using a collection view?
I don't think it matters but I'm running in iOS simulator on Mac iOS 16.2.
The white space at the bottom of the screen is iOS Page UseSafeArea in iOS. However, it is not yet implemented in Maui and you can track the MAUI issue here: https://github.com/dotnet/maui/issues/5856.
As an alternative workaround for now, you can set the Page Padding value to remove the bottom white space. In the OnAppearing Method, set the safeInsets of the page:
protected override void OnAppearing()
{
base.OnAppearing();
DeviceSafeInsetsService d = new DeviceSafeInsetsService();
double topArea = d.GetSafeAreaTop();
double bottomArea = d.GetSafeAreaBottom();
var safeInsets = On<iOS>().SafeAreaInsets();
safeInsets.Top = -topArea;
safeInsets.Bottom = -bottomArea;
Padding = safeInsets;
}
And then write platform specific code to get the topArea and bottomArea value.
1.Create DeviceSafeInsetsService.cs in Project folder.
public partial class DeviceSafeInsetsService
{
public partial double GetSafeAreaTop();
public partial double GetSafeAreaBottom();
}
2.And then under the Project/Platform/iOS folder, create a iOS specific class DeviceSafeInsetsService.cs:
public partial class DeviceSafeInsetsService
{
public partial double GetSafeAreaBottom()
{
if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
{
UIWindow window = UIApplication.SharedApplication.Delegate.GetWindow();
var bottomPadding = window.SafeAreaInsets.Bottom;
return bottomPadding;
}
return 0;
}
public partial double GetSafeAreaTop()
{
if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
{
UIWindow window = UIApplication.SharedApplication.Delegate.GetWindow();
var TopPadding = window.SafeAreaInsets.Top;
return TopPadding;
}
return 0;
}
}
For more details, you can refer to this sample .NET MAUI Platform Code Sample.
Set your Corner Radius property to 0 in your button control's property definition
<Button
CornerRadius="0"
Text="Test2"
VerticalOptions="Fill"
BackgroundColor="Red"/>

How to Change the MenuItem Colors of Forms ViewList in iOS ViewCellRenderer?

Is there any way to Change the color of ContextAction Menus added in Xamarin.Forms Xaml file. IsDestructive="True" sets the menu color to Red. But i need another menu to look like Green or some other color.
Here is my Forms Xaml code..
<ListView x:Name="planList" ItemsSource="{x:Static local:SampleData.PLAN_DATA}" RowHeight="150" HorizontalOptions="FillAndExpand">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.ContextActions>
<MenuItem Clicked="OnEditClick" Text="Edit" CommandParameter="{Binding .}"/> <!-- THIS HAS TO BE GREEN COLOR -->
<MenuItem Clicked="OnDeleteClick" Text="Delete" IsDestructive="True" />
</ViewCell.ContextActions>
<ViewCell.View>
<StackLayout Orientation="Vertical" HorizontalOptions="Start" VerticalOptions="FillAndExpand">
<!--Non Editable State-->
<StackLayout Orientation="Horizontal" Spacing="28" IsVisible="{Binding isNotSaveState}">
<Frame WidthRequest="130" HeightRequest="50" BackgroundColor="#151617" HorizontalOptions="Start">
<Label Text="{Binding from}" TextColor="#ff9600" FontSize="Medium" FontFamily="Helvetica"/>
</Frame>
</StackLayout>
<!--Editable State-->
<StackLayout Orientation="Horizontal" Spacing="0" IsVisible="{Binding isSaveState}">
<StackLayout Orientation="Horizontal" Spacing="5">
<Label Text="From" TextColor="#838288" FontSize="Medium" FontFamily="Helvetica"/>
<Entry Text="" BackgroundColor="Red"/>
</StackLayout>
<Button Text="Save" BackgroundColor="Green" CommandParameter="{Binding .}" Clicked="onSaveClick" />
</StackLayout>
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Here is my Renderer..
[assembly: ExportRenderer(typeof(MyApp.Views.Cells.CustomViewCell), typeof(MyApp.iOS.Views.Cells.CustomViewCellRenderer))]
namespace MyApp.iOS.Views.Cells
{
public class CustomViewCellRenderer : ViewCellRenderer
{
public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
{
UITableViewCell cell = base.GetCell(item, reusableCell, tv);
// I have no Idea how to access the Swipe Menus from Renderer
//cell.EditingAccessory
//cell.EditingAccessoryView
return cell;
}
}
}
Xamarin implements the context menu by a native cell ContextActionsCell subclassing the UITableViewCell.
However, as of today Xamarin.Forms.Platform.iOS (1.4.0.6340-pre2) assembly, the ContextActionsCell that setups the gesture and buttons is still an internal class, which is not accessible or inheritable for changing anything.
BUT WAIT!
Still, you may use Reflection to change above internal stuff.
Example:
// Get UIImage with a green color fill
CGRect rect = new CGRect (0, 0, 1, 1);
CGSize size = rect.Size;
UIGraphics.BeginImageContext (size);
CGContext currentContext = UIGraphics.GetCurrentContext ();
currentContext.SetFillColor (0, 1, 0, 1);
currentContext.FillRect (rect);
var backgroundImage = UIGraphics.GetImageFromCurrentImageContext ();
currentContext.Dispose ();
// This is the assembly full name which may vary by the Xamarin.Forms version installed.
// NullReferenceException is raised if the full name is not correct.
var t = Type.GetType("Xamarin.Forms.Platform.iOS.ContextActionsCell, Xamarin.Forms.Platform.iOS, Version=1.3.1.0, Culture=neutral, PublicKeyToken=null");
// Now change the static field value!
var field = t.GetField ("destructiveBackground", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
field.SetValue (null, backgroundImage);
Note 1: This will change the destructive background colors of all context menu.
Note 2: If you also want to change the normal color, the field name is normalBackground.
Note 3: Xamarin may make these classes internal with a purpose that the API and behaviours may change in the future. Above example may break in coming releases.
For Xamarin.Forms.2.3.3.193 & Xamarin.Forms.Platform.iOS (2.x) version number Version=2.0.0.0 and field names Case changed to NormalBackground & DestructiveBackground
using System;
using CoreGraphics;
using Foundation;
using UIKit;
using Xamarin.Forms.Platform.iOS;
using Xamarin.Forms;
using System.Reflection;
[assembly: ExportRenderer(typeof(ViewCell), typeof(App.Renderers.CustomViewCellRenderer))]
namespace App.Renderers
{
public class CustomViewCellRenderer : ViewCellRenderer
{
public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
{
UITableViewCell cell = base.GetCell(item, reusableCell, tv);
try
{
// This is the assembly full name which may vary by the Xamarin.Forms version installed.
// NullReferenceException is raised if the full name is not correct.
var globalContextViewCell = Type.GetType("Xamarin.Forms.Platform.iOS.ContextActionsCell, Xamarin.Forms.Platform.iOS, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null");
// Now change the static field value! "NormalBackground" OR "DestructiveBackground"
if(globalContextViewCell != null)
{
var normalButton = globalContextViewCell.GetField("NormalBackground", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
if (normalButton != null)
{
normalButton.SetValue(null, getImageBasedOnColor("ff9500"));
}
var destructiveButton = globalContextViewCell.GetField("DestructiveBackground", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
if (destructiveButton != null)
{
destructiveButton.SetValue(null, getImageBasedOnColor("B3B3B3"));
}
}
}
catch (Exception e)
{
Console.WriteLine("Error in setting background color of Menu Item : " + e.ToString());
}
return cell;
}
private UIImage getImageBasedOnColor(string colorCode)
{
// Get UIImage with a green color fill
CGRect rect = new CGRect(0, 0, 1, 1);
CGSize size = rect.Size;
UIGraphics.BeginImageContext(size);
CGContext currentContext = UIGraphics.GetCurrentContext();
currentContext.SetFillColor(Color.FromHex(colorCode).ToCGColor());
currentContext.FillRect(rect);
var backgroundImage = UIGraphics.GetImageFromCurrentImageContext();
currentContext.Dispose();
return backgroundImage;
}
}
}

Matching the vertical scroll position of a Grid to a RichEditBox or TextBox

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.

TemplateBinding for Dynamic Controls

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>

Default Layout Orientation when printing XPSs using the WPF XPS Viewer

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();
}

Resources