Adding a new component in c# WPF - c#

I am new to C# and WPF. I wanna add the following element in the page.
<Label HorizontalAlignment="Left" Width="99" MouseMove="Variable_MouseMove" x:Name="VariableLabel">
<Run
Background="red"
Text="Variable"
x:Name="Variable"
/>
</Label>
I wanna add it dynamicly to the Canvas, like that:
Label label = new Label();
Run r = new Run();
label.Children.add(r); // error: label doesn't have the definition of Children
canvas.Children.add(label);
I want to set the background color behind only the text, rather than the whole label, so I use Run as Label child element and set the child element's background.
What should I do? Thanks!

The label don't have Children but in you case you can use Content. So
label.Content = run;
will work

Related

Add XAML programmatically in Windows Phone

I need to add programmatically some UI.
In order to do that I am creating each single Object and adding it to my main grid.
This way (I need to do that in a lambda function):
Deployment.Current.Dispatcher.BeginInvoke(() => {
StackPanel stkpanel = new StackPanel();
stkpanel.Orientation = Orientation.Horizontal;
TextBlock textBlock = new TextBlock();
textBlock.Text = "text1";
Grid myGrid = new Grid();
myGrid.Children.Add(textBlock);
MainPage currentPage = (MainPage)(((App)Application.Current).RootFrame.Content as PhoneApplicationPage);
currentPage.LayoutRoot.Children.Add(myGrid);
...
});
Is there a way to add to my MainPage.xaml another File.xaml and display the result?
I am using silverlight 8.1
Thanks
There some different ways to do that.
UserControl
One way is to create a user Control and use it direct in XAML or instantiate it in the code behind like a standard control. You can find a template in the Add Item dialog in Visual Studio.
Pages
It is also possible to create a second page and Display them in a Frame tag. It is possible in XAML and code behind. Here is an example:
<Frame Margin="0,148,0,0" Name="myFrame"/>
myFrame.Navigate(typeof(BlankPage1));
XamlReader
If you have a partial XAML code, stored in a file you can parse it manual and add the objects to the page. Your XAML must look like the following with the xmlns Attribut
<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Button Content="BTN 1" />
<Button Content="BTN 2" />
<Button Content="BTN 3" />
</StackPanel>
Then you can parse it with XamlReader:
var uri = new Uri("ms-appx:///test.xaml");
var file = await StorageFile.GetFileFromApplicationUriAsync(uri);
var panel = XamlReader.Load(await FileIO.ReadTextAsync(file)) as StackPanel;
root.Children.Add(panel);
Be sure you set the Build Action of the XAML file to Content, if you will use it as an resource. You can also pass directly a string with XAML code to the XamlReader.Load function.

Adding a TextBlock to a Label in C# Code WPF

In my code I am creating a new Label and formatting it and making it a child of a Stacked Panel. But inside of the Label I need to add a Text Block and I am having trouble to find out how to do this.
Using Code only I need to the WPF created by the code to work like this:
<Label Background="#000000" Foreground="#FFFFFF">
<TextBlock TextWrapping="Wrap" Text="Text Here"/>
</Label>
But I can not figure out how to get that TextBlock inside of the Label in the code, what I thought would work isn't working because it is a Label:
NewLabel.Children.Add(NewTextBlock);
But this works when I use it to add the NewLabel to the StackedPanel.
The whole reason I need this to work is because I need text wrapping in the Label, but can't use just the TextBlock or other Control.
Just set the TextBlock as the content of the label to achieve your requirement.
Label lbl = new Label ();
TextBlock txtBlock = new TextBlock ();
txtBlock.TextWrapping = TextWrapping.Wrap;
lbl.Content = txtBlock;
Also you could add a style for "Label" to your Resources which contains a default DataTemplate for type string. So all string content in any Label is wrapped.
<Application.Resources>
<Style TargetType="Label">
<Style.Resources>
<DataTemplate xmlns:sys="clr-namespace:System;assembly=mscorlib" DataType="{x:Type sys:String}">
<TextBlock TextWrapping="Wrap" Text="{Binding}" />
</DataTemplate>
</Style.Resources>
</Style>
</Application.Resources>
Then all you Need to do is set the string Content.
<Label Content="A very long string for my Label" />
or
var Label = new Label { Content = "A very long string for my Label" }

Disabled TextBox Style

I have created a TextBox above a Path-Element (the Path Element draws a rectangular thing, which acts as the design of the textbox). Now I want to disable this TextBox with
valCon.ValueTextBox.IsEnabled = false;
This works so far. However, since I don't want the TextBox to have any Style (no Color, no Borders, etc.), but only a visible Text in it, I'm getting a small problem:
When the TextBox is disabled, it automatically receives a style which I can't get rid of. The Background changes to white, the Opacity changes to around 0.3 and Borders appear.
I can't seem to solve this problem by adding
valcon.ValueTextBox.Background = new SolidColorBrush(Colors.Transparent);
valcon.ValueTextBox.BorderBrush = new SolidColorBrush(Colors.Transparent);
etc.
It just seems to ignore this. Does anyone know a solution?
Greetings
Narakuvera
You need to take control over the template to achieve the same
here is a basic template for you with no border and no background TextBox
<TextBox Text="hello">
<TextBox.Template>
<ControlTemplate TargetType="TextBox">
<ScrollViewer Margin="0"
x:Name="PART_ContentHost" />
</ControlTemplate>
</TextBox.Template>
</TextBox>
you can choose to set IsEnabled="False" and it will still remain border less
Code behind approach
ControlTemplate ct = new ControlTemplate(typeof(TextBox));
FrameworkElementFactory sv = new FrameworkElementFactory(typeof(ScrollViewer));
sv.Name = "PART_ContentHost";
ct.VisualTree = sv;
textbox1.Template = ct;
WinRT code behind approach
string template = "<ControlTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" TargetType=\"TextBox\"><ScrollViewer Name=\"PART_ContentHost\" /></ControlTemplate>";
ControlTemplate сt = (ControlTemplate)XamlReader.Load(template);
textbox1.Template = сt;

Using RichTextBlock in FlipView in Metro Style App

I am using standard Visual Studio templates and I have a ItemsDetailPage that contains a FlipView with a RichTextBlock in its DataTemplate.
I want to set the RichTextBlock block to my custom Paragraphs generated in text. I think there is no way to bind RichTextBlocks Block in XAML so I am using code behind. In the Loaded event of RichTextBlock I set its Block, that works ok. But the problem is, the Loaded event gets called only once when the page is displayed. When I "flip" to another item, the selected item of the FlipView changes but the Loaded event does not get called again (I think this is ok).
I tried setting the RichTextBlock in the FlipViews SelectionChanged item but that does not work.
var ind = this.flipView.SelectedIndex;
var flipViewItem = this.flipView.ItemContainerGenerator.ContainerFromIndex(flipView.SelectedIndex);
if (flipViewItem != null)
{
var scroller = FindFirstElementInVisualTree<ScrollViewer>(flipViewItem);
var tb = scroller.FindDescendantByName("richTextColumns").FindDescendantByName("richTextBlock") as RichTextBlock;
SetRichContent(tb, (flipView.SelectedItem as ArticleViewModel).HtmlContent);
}
The SetRichContent gets called, sets the RichTextBlocks Blocks but visually they do not change and after a few flips, the whole app crashes without any additional information.
So my question is, how do I get my own code called on the RichTextBlock with each flip (seleced item change)?
You can bind rich text boxes. Make sure your data context is set properly. We need to see more code to make an appropriate answer.
<RichTextColumns>
<RichTextColumns.ColumnTemplate>
<DataTemplate>
<RichTextBlockOverflow Width="400" Margin="50,0,0,0"/>
</DataTemplate>
</RichTextColumns.ColumnTemplate>
<RichTextBlock Width="400">
<Paragraph>
<Run Text="{Binding Content}"/>
</Paragraph>
</RichTextBlock>
</RichTextColumns>

how to initialize new textbox in specific position in wpf

I am using InkCanvas control and I want to add a textbox in it as a child in specific position I succeeded to add it but not in the correct position ? how I can transform it or any another method ?
You can use the attached properties Left and Top like so:
var myTextBox = new TextBox();
myCanvas.Children.Add( myTextBox );
InkCanvas.SetLeft( myTextBox, someLeftValue );
InkCanvas.SetTop( myTextBox, someTopValue );
The InkCanvas isn't a panel type (note it inherits from FrameworkElement), but it does contain attached properties (as Ed S. mentioned) that let you position children as though it were a Canvas panel:
<InkCanvas>
<TextBox InkCanvas.Top="50" InkCanvas.Left="50"/>
</InkCanvas>
Alternatively, you can also insert a panel as the child of the InkCanvas. For example:
<InkCanvas>
<Canvas>
<TextBox Canvas.Top="50" Canvas.Left="50"/>
</Canvas>
</InkCanvas>

Categories