.NET MAUI : Override the default style of a windows view (TextBox) - xaml

I want to create a custom Entry with a completely personalized visual.
For this, I created a CustomEntryHandler to modify the native view of the windows platform but I can't override the basic windows style which imports some effects :
The background color that changes on over
The bottom border that is displayed when entry is focused
...
I think I understood that this style comes from the default style of windows, in the generic.xaml file.
Does anyone know how I can override this ?
protected override TextBox CreatePlatformView()
{
var nativeView = new TextBox();
nativeView.Margin = new Microsoft.UI.Xaml.Thickness(0, 0, 0, 0);
nativeView.FocusVisualMargin = new Microsoft.UI.Xaml.Thickness(0, 0, 0, 0);
nativeView.BorderThickness = new Microsoft.UI.Xaml.Thickness(0,0,0,0);
nativeView.Padding = new Microsoft.UI.Xaml.Thickness(0, 0, 0, 0);
nativeView.CornerRadius = new Microsoft.UI.Xaml.CornerRadius(0);
nativeView.Background = new SolidColorBrush(Colors.Transparent);
return nativeView;
}
Screenshot of the entry focused with code above
UPDATE 11/10/22 : I also want to remove the Clear button of the TextBox.
Thanks in advance.

The easiest way would be to write a new Style and apply it to your control using this code:
var nativeView = new TextBox();
nativeView.Style = Application.Current.Resources["MyCustomTextBoxStyle"];
In your App.xaml, you need to add the following style:
<Style x:Key="MyCustomTextBoxStyle" TargetType="TextBox">
<!-- Your textbox style -->
</Style>
You can find the standard WinUI 2 TextBox style here. If you would like to remove the clear button, you could remove the button that is part of the TextBoxStyle here.

Related

Custom IntelliCode prediction with Visual Studio extension

I would like to add the custom IntelliCode prediction/inline suggestion in Visual Studio with extension. In VSCode, I can use vscode.InlineCompletionProvider/InlineCompletionItem to do that. What's the class/method that would do the same things in Visual Studio extension?
I had the same requirement but I did not find any API for that.
However, what you can do is use adornments to draw a text that looks like code.
Define the adornment:
[Export(typeof(AdornmentLayerDefinition))]
[Name("TextAdornment1")]
[Order(After = PredefinedAdornmentLayers.Text)]
private AdornmentLayerDefinition editorAdornmentLayer;
Get the layer and add a TextBlock:
_layer = view.GetAdornmentLayer("TextAdornment1");
// triggeringLine is your current line
var geometry = _view.TextViewLines.GetMarkerGeometry(triggeringLine.Extent);
var textBlock = new TextBlock
{
Width = 600,
Foreground = _textBrush,
Height = geometry.Bounds.Height,
FontFamily = new FontFamily(_settings.FontFamily),
FontSize = _fontSize,
Text = $"Your completion text"
};
// put the box at the end of your current line
Canvas.SetLeft(textBlock, geometry.Bounds.Right);
Canvas.SetTop(textBlock, geometry.Bounds.Top);
_layer.AddAdornment(AdornmentPositioningBehavior.TextRelative, triggeringLine.Extent, "your tag", textBlock, (tag, ui) => { });
You can get the current editor settings as follows:
// Get TextEditor properties
var propertiesList = dte.get_Properties("FontsAndColors", "TextEditor");
// Get the items that are shown in the dialog in VS
var itemsList = (FontsAndColorsItems)propertiesList.Item("FontsAndColorsItems").Object;
// Get color for comments
var commentItem = itemsList.Cast<ColorableItems>().Single(i => i.Name=="Comment");
var colorBytes = BitConverter.GetBytes(commentItem.Foreground);
var commentColor = Color.FromRgb(colorBytes[2], colorBytes[1], colorBytes[0]);
// Get editor BG
var textItem = itemsList.Cast<ColorableItems>().Single(i => i.Name == "Plain Text");
var bgColorBytes = BitConverter.GetBytes(textItem.Background);
var bbgColor = Color.FromRgb(bgColorBytes[2], bgColorBytes[1], bgColorBytes[0]);
// Get font size in points
var fontSize = (short)propertiesList.Item("FontSize").Value;
// Get current font family
var fontFamily = (string)propertiesList.Item("FontFamily").Value;
The issue with this approach is that the styling and font size slightly differs from the editor. Even if you use the editor setting.
However I think that IntelliCode and GitHub Copilot use another technique. As you can see here:
GitHub Coilot
It seems as the whole code is already inserted to the editor but has a special styling/behaviour. So it is possible somehow, but I don't how to achieve that.
For more information on adornments look here for example:
Visual Studio Text Adornment VSIX using Roslyn
You can implement your custom language-based statement completion. Please take a look at:
Walkthrough: Displaying Statement Completion
Implementing Custom XAML Intellisense VS2017 Extension
Visual-studio – Custom Intellisense Extension
Custom Intellisense Extension
Another different option is using GitHub Copilot extension for Visual Studio, it predicts code using AI

Background Image Is Other Image Vb.net [duplicate]

In my C# Form I have a Label that displays a download percentage in the download event:
this.lblprg.Text = overallpercent.ToString("#0") + "%";
The Label control's BackColor property is set to be transparent and I want it to be displayed over a PictureBox. But that doesn't appear to work correctly, I see a gray background, it doesn't look transparent on top of the picture box. How can I fix this?
The Label control supports transparency well. It is just that the designer won't let you place the label correctly. The PictureBox control is not a container control so the Form becomes the parent of the label. So you see the form's background.
It is easy to fix by adding a bit of code to the form constructor. You'll need to change the label's Parent property and recalculate it's Location since it is now relative to the picture box instead of the form. Like this:
public Form1() {
InitializeComponent();
var pos = label1.Parent.PointToScreen(label1.Location);
pos = pictureBox1.PointToClient(pos);
label1.Parent = pictureBox1;
label1.Location = pos;
label1.BackColor = Color.Transparent;
}
Looks like this at runtime:
Another approach is to solve the design-time problem. That just takes an attribute. Add a reference to System.Design and add a class to your project, paste this code:
using System.ComponentModel;
using System.Windows.Forms;
using System.Windows.Forms.Design; // Add reference to System.Design
[Designer(typeof(ParentControlDesigner))]
class PictureContainer : PictureBox {}
You can just use
label1.Parent = pictureBox1;
label1.BackColor = Color.Transparent; // You can also set this in the designer, as stated by ElDoRado1239
You can draw text using TextRenderer which will draw it without background:
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
TextRenderer.DrawText(e.Graphics,
overallpercent.ToString("#0") + "%",
this.Font,
new Point(10, 10),
Color.Red);
}
When overallpercent value changes, refresh pictureBox:
pictureBox1.Refresh();
You can also use Graphics.DrawString but TextRenderer.DrawText (using GDI) is faster than DrawString (GDI+)
Also look at another answer here and DrawText reference here
For easy for your design.
You can place your label inside a panel. and set background image of panel is what every image you want. set label background is transparent
After trying most of the provided solutions without success, the following worked for me:
label1.FlatStyle = FlatStyle.Standard
label1.Parent = pictureBox1
label1.BackColor = Color.Transparent
You most likely not putting the code in the load function. the objects aren't drawn yet if you put in the form initialize section hence nothing happens.
Once the objects are drawn then the load function runs and that will make the form transparents.
private void ScreenSaverForm_Load(object sender, EventArgs e)
{
label2.FlatStyle = FlatStyle.Standard;
label2.Parent = pictureBox1;
label2.BackColor = Color.Transparent;
}
One way which works for everything, but you need to handle the position, on resize, on move etc.. is using a transparent form:
Form form = new Form();
form.FormBorderStyle = FormBorderStyle.None;
form.BackColor = Color.Black;
form.TransparencyKey = Color.Black;
form.Owner = this;
form.Controls.Add(new Label() { Text = "Hello", Left = 0, Top = 0, Font = new Font(FontFamily.GenericSerif, 20), ForeColor = Color.White });
form.Show();
Using Visual Studio with Windows Form you may apply transparency to labels or other elements by adding using System.Drawing; into Form1.Designer.cs This way you will have Transparency available from the Properties panel ( in Appearance at BackColor ). Or just edit code in Designer.cs this.label1.BackColor = System.Drawing.Color.Transparent;

Add a footer to an exported OxyPlot plot

I am using OxyPlot to export plots.
When I export them, I want to add a footer to these plots with information like the path it is saved, a time-stamp, and so on...
Right now I am doing this by creating an extra X-axis on a different position-tier and then setting the sizes of all ticks and labels to zero except for the title font-size.
This works, but as you might imagine, this is quite hacky and does not look that good (as you cannot set for example the aligning).
So my question is, is there a possibility to add such a footer to the exported plot?
EDIT:
var xAxis = new OxyPlot.Axes.LinearAxis
{
Position = AxisPosition.Bottom,
PositionTier = 1,
Title = "Footer: i.e. path to my file",
MinorTickSize = 0.0,
MajorTickSize = 0.0,
FontSize = 0.0,
TitleFontSize = 12,
AxisDistance = 10
};
This is the workaround I mentioned.
I create an axis at position-tier 1, which is below the first one and then disable all visuals of it except the title.
And in the end I add it to my plotmodel pm.Axes.Add(xAxis).
To export my plotmodel I use PdfExporter like this:
using (var stream = File.Create(testFile.pdf))
{
PdfExporter.Export(pm, stream, 800, 500);
}
Greetings
Chriz
Just had to do the same thing with my project and thought I'd share how I managed it for anyone else in need of a footer.
I couldn't find any built in OxyPlot methods to add a header or footer but if you use OxyPlot.PDF it's built on top of PDFSharp and you have more options to customize your PDF export.
Remove any previous reference to OxyPlot.Pdf in your project.
Download OxyPlot.Pdf source code from: https://github.com/oxyplot/oxyplot
In your project in VS, right click your solution in 'Solution Explorer' and Add Existing Project.
Navigate to the downloaded source code and add OxyPlot.Pdf.csproj
Right click your project and Add Reference
Select 'Projects' on the left and check the box for OxyPlot.Pdf on the right. Hit OK.
Check that it's working by building and running project.
Go to PdfRenderContext.cs file and find the PdfRenderContext method near the top.
Add the code below then build and run your project.
This code creates a MigraDoc Document and then merges it with the OxyPlot PdfDocument.
public PdfRenderContext(double width, double height, OxyColor background)
{
//*** Original Code - Don't change **//
this.RendersToScreen = false;
this.doc = new PdfDocument();
var page = new PdfPage { Width = new XUnit(width), Height = new XUnit(height) };
this.doc.AddPage(page);
this.g = XGraphics.FromPdfPage(page);
if (background.IsVisible())
{
this.g.DrawRectangle(ToBrush(background), 0, 0, width, height);
}
//*** New Code to add footer **//
Document myDoc = new Document();
Section mySection = myDoc.AddSection();
Paragraph footerParagraph = mySection.Footers.Primary.AddParagraph();
footerParagraph.AddText(DateTime.Now.ToShortDateString());
footerParagraph.Format.Alignment = ParagraphAlignment.Right;
MigraDoc.Rendering.DocumentRenderer docRenderer = new MigraDoc.Rendering.DocumentRenderer(myDoc);
docRenderer.PrepareDocument();
docRenderer.RenderObject(g, XUnit.FromInch(9.5), XUnit.FromInch(8), "1in", footerParagraph);
}
When you export the PDF a date stamp is now added to the lower right corner of the PDF. Note that I was working with landscape 8.5x11 inch paper so you may need to change position if you don't see it on the plot. Upper left corner is 0,0. Once it's working, build the OxyPlot.Pdf project to create the dll and then you can add it as a reference to your project and remove the source code.
Result:

Is there a way to Edit the TextColor of the text inside Toasts in Windows8

Is there a way to Edit the TextColor of the text inside Toasts in Windows8 ?
Created like this.
var toastXml = new XmlDocument();
var title = toastXml.CreateElement("toast");
var visual = toastXml.CreateElement("visual");
visual.SetAttribute("version", "1");
visual.SetAttribute("lang", "en-US");
var binding = toastXml.CreateElement("binding");
binding.SetAttribute("template", "ToastImageAndText02");
image.SetAttribute("src", ActualPathToSet);
//Here the Text is assigned
var heading = toastXml.CreateElement("text");
heading.SetAttribute("id", "1");
heading.InnerText = R.GetResourceString("Hello World");
title.AppendChild(visual);
visual.AppendChild(binding);
binding.AppendChild(image);
binding.AppendChild(heading);
var toast = new ToastNotification(toastXml);
I have created a toast like above and want to change the TextColor property.
using C# +XAML + Win8
Change foreground color in manifest file.
I think this is not possible because the Toast Notification is a system internal function and the color is given by the user setting background color.

Using WriteableBitmapEx

I am currently developing metro apps and I need to write text On images.
I found this http://writeablebitmapex.codeplex.com/
But I am new to XAML and dosent know how to use it specifically.
So can anyone say me how do I use it in order to write text on image.
As I have asked this question on MSDN but I have no reply yet.
Edit:
If I use as Muad'Dib I am getting the error as seen in below screenshot:
The Error is: 'Writeable Bitmap Extensions' is ambiguous in the namespace 'System.Windows.Media.Imaging'
there is one possible solution in the Discussions area for WriteableBitmapEx
here is the code from that "article":
public static void DrawText(this WriteableBitmap wBmp,Point at, string text,double fontSize,Color textColor)
{
TextBlock lbl = new TextBlock();
lbl.Text = text;
lbl.FontSize = fontSize;
lbl.Foreground = new SolidColorBrush(textColor);
WriteableBitmap tBmp = new WriteableBitmap(lbl, null);
wBmp.Blit(at, tBmp, new Rect(0, 0, tBmp.PixelWidth, tBmp.PixelHeight), Colors.White, System.Windows.Media.Imaging.WriteableBitmapExtensions.BlendMode.Alpha);
}