I am a complete "weekend warrior" to programming so go gentle on me, please...
I want to achieve a simple task, which I had no problem with in plain C# (TextBox.Text = "Something";)
I have a textbox and a textblock in XAML, and I want to populate them from C#, simple as that - run the web app and pull the predefined strings from the C# code. I have been searching for 2 days now and can't find a straight answer. I don't want any triggers (buttons), just filling e.g. textbox on load with a C# string. A simple code example on both XAML and C# side would be greatly appreciated!
Cheers,
Sasa
Not sure if I'm understanding your question...
<!--xaml-->
<TextBox x:Name="txtMyTextBox"/>
// C#
// Window constructor
public MyWindow()
{
InitializeComponent();
txtMyTextBox.Text = "Something";
}
One simple way to achieve what you try to achieve (if I understood correctly), is to add the UI elements to your window and set a Name for each of them. This way, you can access them in your code-behind as seen below.
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid>
<TextBox Name="TextBox1" HorizontalAlignment="Left" Height="23" Margin="37,37,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
<TextBlock Name="TextBlock1" HorizontalAlignment="Left" Margin="48,100,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Height="103" Width="239"/>
</Grid>
</Window>
While there are certainly more "refined" ways to achieve the same, once you named your UI elements in xaml, you can access them just as other object instances in your code-behind.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
TextBox1.Text = "Hello TextBox1!";
TextBlock1.Text = "Hello TextBlock1!";
}
}
}
Related
I am relatively new to this platform, so forgive me for my lack of professionalism.
I encountered a problem while creating one of my first WPF applications.
I managed to include some buttons in MainWindow and run it, but I spotted some bugs, so I tried to start from the scratch.
I decided to run an empty window, but then i saw the previous "buggy" window at runtime. Since then, no matter what i change in MainWindow.xaml file i get the same old result.
I tried to chceck whether my program compiles, and for what I know it does.
Unfortunately I erased old xaml code responsible for "buggy" window, but I can recall it was something like this.
<Window x:Class="ProjektPO.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ProjektPO"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<StackPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button x:Name="A" Content="B" Click="A_Click"/>
</Grid>
</StackPanel>
</Grid>
</Window>
And the .cs file (almost default)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ProjektPO
{
/// <summary>
/// Logika interakcji dla klasy MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void A_Click(object sender, RoutedEventArgs e)
{
}
}
}
Program compiles and dispalys old "buggy" Window.
I want to play video directly from the server in MediaElement. (The source will be the server)
I have a URL of the server:
http://videotherapy.co/dev/vt/api/dispatcher.php
And post the following json:
{"videoId":"22-1","api":"get-training-video"}
(where 22-1 is the videoId)
XAML code:
<Window x:Class="MediaElementApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="467.91" Width="1300">
<Grid>
<MediaElement x:Name="mediaElement" HorizontalAlignment="Left" Height="418" Margin="246,10,0,0" VerticalAlignment="Top" Width="1036" LoadedBehavior="Manual" UnloadedBehavior="Stop" Source="Images\Wildlife.wmv" />
<Button x:Name="play" HorizontalAlignment="Left" Margin="538,161,0,0" VerticalAlignment="Top" Width="100" Height="84" Click="play_Click" >
<Button.Background>
<ImageBrush ImageSource="Images/smiley.jpg"/>
</Button.Background>
</Button>
</Grid>
c# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MediaElementApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void play_Click(object sender, RoutedEventArgs e)
{
mediaElement.Play();
}
}
}
How to do this?
I would like for help.
The MediaElement accepts a URI as Source. Like this, it can stream the video from the web to the client application.
If this is somehow not possible in your case. You'll have to download the video to a File. Then pass the location of this file to the Source property of the MediaElement
Let's say, I create a page MyPage in a WPF application MyApp with Visual Studio 2012 Express.
Very often, when I try to access newly created elements of MyPage.xaml in MyPage.xaml.cs, I get an error message like
The name “group_combobox” does not exist in the current context
This happens even though other elements of the same page / the same context do exist and are available in my C# sharp code editor window.
To give you an example of the problem, see the following MyPage.xaml and MyPage.xaml.cs which are returning the error message, when editing the MyPage.xaml.cs file:
MyPage.xaml
<Page x:Class="MyApp.MyPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="768" d:DesignWidth="1024"
Title="MyApp - MyPage" Width="Auto" Height="Auto">
<Button x:Name="MyPage_back_button" Content="Back" Margin="10,100,10,0" VerticalAlignment="Top" FontSize="24" Height="50"/>
<StackPanel Margin="0" x:Name="settings_stackpanel">
<GroupBox Header="Group" VerticalAlignment="Top" FontSize="24" Margin="10" Height="100">
<ComboBox x:Name="group_combobox" Height="62" VerticalAlignment="Top" Margin="0" BorderBrush="{x:Null}" Background="{x:Null}" VerticalContentAlignment="Center"/>
</GroupBox>
</StackPanel>
</Page>
MyPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MyApp
{
public partial class MyPage : Page
{
public MyPage()
{
Debug.WriteLine("MyPage");
InitializeComponent();
group_combobox.Items.Clear(); // <-- error: The name “group_combobox” does not exist in the current context
string test = MyPage_back_button.ToString(); // <-- no error
}
}
}
As you can see, the error is only thrown for one of two elements from the same page. I think, there is somehow somewhere described how this "context" looks and what it contains. And at a certain point there is some kind of "synchronization" or something like that.
I noticed this behaviour before, and it solved "magically" that I think I somehow accidentally fired that trigger or the mechanism that is responsible for this synchronization.
Do you know how to trigger that kind of synchronization and how to access the information about "the current context"?
p.s. Rebuilding the project did not solve the problem
I'm going round in circles here. I've kind of got the hang of XmlDataProvider bindings but the file I'm using seems too large to bind dynamically (50Mb doesn't work; 2Mb works). So instead I have the data loaded into classes using code generated from the XSD.
However, I can't get binding to CLR objects to work, due to my lack of knowledge. I'm using Visual Studio 2008 Pro, C# and .Net 3.5.
Here's the XAML file:
<Window x:Class="WpfObjectText.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfObjectText"
Title="Window1" Height="300" Width="300">
<Grid>
<Grid.Resources>
<ObjectDataProvider x:Key="simpleBinding" ObjectType="{x:Type local:ExampleClass}"/>
</Grid.Resources>
<StackPanel>
<TextBox Name="textBox1" Text="{Binding Path=simpleBinding}" />
</StackPanel>
</Grid>
</Window>
And the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfObjectText
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public ExampleClass TestInstance = new ExampleClass("Hello, world!");
public Window1()
{
InitializeComponent();
}
}
public class ExampleClass
{
public string TestString { get; set; }
public ExampleClass(string initialText)
{
TestString = initialText;
}
}
}
I've deliberately kept it simple so I can take baby steps. All I want to do here is populate the textbox from an instance of ExampleClass, and have the TestString field updated if the textbox changes (ie bidirectional). I know I can set MethodName in the binding which works to a certain extent in ListBoxes but that doesn't seem to imply bidirectional to me. Coming from a Delphi7 Win32 programmer, this is alien territory for me!
Assistance appreciated.
These are the necessary changes:
<TextBox Name="textBox1" Text="{Binding Path=TestString}" />
and then in the constructor:
DataContext = TestInstance;
If my understanding of the question is correct, you don't need Grid.Resources section at all.
That's me again with my bindings :)
Here is the problem, I need to have on my GRID two controls connected with a LINE. So I can move with mouse one of the controls around GRID and LINE, that connect this two controls must replace immediately while moving.
Any ideas? I thought that calculate new X1,Y1,X2,Y2 of the LINE on every 1px move impossible and very speedless... So I think that there is the way to create BINDINGS for LINE's X1,Y1,X2,Y2, such as:
x1={Binding firstCtrl.Position.X+firstCtrl.Width/2}
But such binding is very hard (for me) even in XAML, but I need to create such binding dynamically in C# code.
Need your advice again, how to create such binding in C# or there is another way to realize my idea?
P.S."I don't need whole code for that, just description and, maybe, simple example of code."
Thanks a lot.
You could use a MultiValueConverter to gather the points of interest and return the X or Y point as needed.
Here is a good blog post discussing their use.
Try this:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ResourceDictionary>
<ControlTemplate x:Key="template1">
<Ellipse Width="30" Margin="-15 -15" Height="30" Fill="Black"/>
</ControlTemplate>
</ResourceDictionary>
</Window.Resources>
<Canvas Name="myCanvas">
<Thumb Name="myThumb" DragDelta="onDragDelta" Canvas.Left="0" Canvas.Top="30" Template="{StaticResource template1}"/>
<Thumb Name="myThumb2" DragDelta="onDragDelta" Canvas.Left="400" Canvas.Top="30" Template="{StaticResource template1}"/>
<Line X1="{Binding ElementName=myThumb,Path=(Canvas.Left)}" Y1="{Binding ElementName=myThumb,Path=(Canvas.Top)}" X2="{Binding ElementName=myThumb2,Path=(Canvas.Left)}" Y2="{Binding ElementName=myThumb2,Path=(Canvas.Top)}" Stroke="Black" />
</Canvas>
code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
void onDragDelta(object sender, DragDeltaEventArgs e)
{
var i = sender as UIElement;
if (i != null)
{
Canvas.SetLeft(i, Canvas.GetLeft(i) + e.HorizontalChange);
//Canvas.SetTop(myThumb, Canvas.GetTop(myThumb) + e.VerticalChange);
}
}
}
}
EDIT:
Explanation: this has two draggable circles (x-axis only) and a line connecting both. I've created a binding for the X-Num,Y-Num properties and bound them to the Canvas.Top/Left attached properties of the thumb objects (using ElementName Binding). This places both ends of the line in the 0,0 coords of each object. So I used a negative margin to put the circle's center in 0,0.
Hope that helps.