There are 2 pages in my UWP project.
In the following page, I announce a WebView object.
<Page
x:Class="UniversalMarkdownTestApp.WebViewPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UniversalMarkdownTestApp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<WebView Name="WebContent" Grid.Row="0" x:FieldModifier="public"/>
</Grid>
</Page>
Now I want to access this object in other page. How can I achieve this?
You could access this object in other page by the following code:
MainPage mainpage = new MainPage();
var webv = mainpage.WebContent;
But as AbsoluteSith said, this object's instance has been created, if you want to add it to the new page, you could not add directly.
You would need to use this object's property value to create a new object. Please see the following code:
MainPage mainpage = new MainPage();
var webv = mainpage.WebContent;
WebView wv = new WebView();
wv.Source = webv.Source;
grid.Children.Add(wv);
There's another other way to get object in other pages. You could pass object as parameter when navigating. See the following code:
rootFrame.Navigate(typeof(BlankPage),WebContent);
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
WebView wv = new WebView();
wv.Source = ((WebView)e.Parameter).Source;
gd.Children.Add(wv);
}
Here, I still not sure why you want to do this. In general, I don't suggest get controls between the pages. Maybe, if you could tell us your requirement, or What kind of effect you want to achieve, there might be some better solutions.
Related
I have the following situation. I want to show a list of strings. In order to achieve that, I have a ListView bound to a collection of strings. In this collection, there are some empty strings. What I want is to show the following text when a empty string is present: "-empty-". This is what I got so far (the source code is for demonstration purpose only):
EmptyStringConverter.cs
public class EmptyStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value is string && string.IsNullOrWhiteSpace((string)value))
{
return "-empty-";
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
MainPage.xaml
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<local:EmptyStringConverter x:Key="EmptyStringConverter" />
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ListView x:Name="ListView">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource EmptyStringConverter}}" Margin="0,0,0,5" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Page>
MainPage.xaml.cs
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
var source = new[] { "", "String 1", "String 2" };
ListView.ItemsSource = source;
}
}
When a put a breakpoint in the Convert method in EmptyStringConverter class, the method is called in every single item except in the empty string. How can I achieve what I want?
Well the issue was in the place I'd check the last. It's your Legacy Binding that's causing the issue. I tried a code snippet myself and then I replaced it with yours piece by piece. The below line uses legacy binding
Text="{Binding Converter={StaticResource EmptyStringConverter}}"
Since you are using UWP you can switch to a Compile time binding that'll fix your problem your modified ListView XAML would be:
<ListView x:Name="ListView" >
<ListView.ItemTemplate>
<DataTemplate x:DataType="x:String">
<TextBlock Text="{x:Bind Converter={StaticResource EmptyStringConverter},Mode=OneTime}" Margin="0,0,0,5" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Please pay attention at two things:
the Text section of the Textbox in the DataTemplate, it uses x:Bind instead of Binding. Please do note that compile time binding is a oneTime binding by default (unless you explicitly mention the Mode) where as the Legacy Binding is a OneWay binding by default. For More information on compile time binding follow: xBind markup extension.
If you notice the DataTemplate declaration holds a DataType property, that helps the compile time binder to know what kind of data is it expecting. For more information on DataType follow: xBind markup extension.
All that being said, I would highly recommend using the Data Binding approach instead of the ListView.ItemSource=source as with the new Compile Time binding, alot of conversions are handled by the binding engine itself leading to less code and effort on your end. I've put up a sample on github for the same you can check it out: EmptyStringDemo
I'm writing a UserControl, which I intend to use on several pages. It should encapsulate the behaviour to be the same for all pages. But the content and the layout should be different.
On the UserControl I have a ListView whoes ItemSource is bound to a CollectionViewSource with grouping enabled.
<ListView
ItemSource="{Binding Source={StaticResource Collection}}"
ItemTemplate="{Binding GroupedDataTemplate}">
<ListView.GroupStyle>
<GroupSytele HeaderTemplate="{Binding HeaderDataTemplate}"/>
</ListView.GroupStyle>
</ListView>
The UserControl has the DependencyProperties "GroupedDataTemplate", "HeaderDataTemplate" for the layout and one "GroupedCollection" for the data.
On the page, where the UserControl is used, I defined the DataTemplates like:
<controls:MyUserControl
GroupedCollection="{Binding DataContext.MyDataCollection, ElementName=thePage}">
<controls:MyUserControl.GroupedDataTemplate>
<DataTemplate>
<TextBlock Text="{Binding Description}"/>
</DataTemplate>
</controls:MyUserControl.GroupedDataTemplate>
<controls:MyUserControl.HeaderDataTemplate>
<DataTemplate>
<TextBlock Text="{Binding Key}"/>
</DataTemplate>
</controls:MyUserControl.HeaderDataTemplate>
</controls:MyUserControl>
My problem is, that the DataTemplate definition for "GroupedDataTemplate" works as expected, the description is shown. But for the "HeaderDataTemplate" it doesn't, it is shown only the ToString()-representation of the object.
The setter of the "HeaderDataTemplate" is called and the DataTemplate is assigned to the DependencyProperty of the UserControl.
If I replace the UserControl with the ListView itself, it works as expceted. Thus the binding works propperly to the Description and the Key, but it will only work for description if it is inside the UserControl.
For test purposes I have added a converter to the binding of the Key in the page and it is never called. I all cases, where I define a DataTemplate for an ItemTemplate (ListView or GridView) it works, but is doesn't for the HeaderTemplate of the GroupStyle.
What is my fault?
Very good question, it seems when you use Binding for the HeaderTemplate of GroupSytele, in the .g.cs file of your UserControl, it doesn't generate the update code for HeaderDataTemplate, it means when you define this HeaderDataTemplate property for example like this:
public static readonly DependencyProperty HeaderDataTemplateProperty = DependencyProperty.Register("HeaderDataTemplate", typeof(DataTemplate), typeof(UserGroupedListView), new PropertyMetadata(null));
public DataTemplate HeaderDataTemplate
{
get { return (DataTemplate)GetValue(HeaderDataTemplateProperty); }
set { SetValue(HeaderDataTemplateProperty, value); }
}
The get never gets called.
A workaround here is that you can change the Binding to x:Bind like this in your UserControl:
<ListView ItemsSource="{Binding Source={StaticResource Collection}}" ItemTemplate="{Binding GroupedDataTemplate}">
<ListView.GroupStyle>
<GroupStyle HeaderTemplate="{x:Bind HeaderDataTemplate}" />
</ListView.GroupStyle>
</ListView>
Basically you've done nothing wrong, but it seems data binding for the HeaderTemplate of GroupStyle can only work when it uses x:Bind.
How can i display Login detail of user across all pages in xamarin portable project(iOS and Andriod). I am not able to implement MasterPage concept as we use to do in ASP.net or Frame in Silverlight.
I have already gone through MasterDetailPage and I think it doesn't fulfill my requirement.
Create a static variable UserName in your App.cs file.
public class App : Application
{
public static bool IsUserLoggedIn { get; set; }
public static string UserName { get; set; }
public App()
{
if (!IsUserLoggedIn)
{
MainPage = new NavigationPage(new LoginPage());
}
else
{
MainPage = new NavigationPage(new MenuPage());
}
}
}
On LoginPage.cs file, store the username in static variable of App.cs file when user login for the first time. I am assuming that you have login page with two entry fields such as username and password field along with a login button. So when user click on login button store the username from entry field as :
App.UserName = usernameEntry.Text.ToString();
On successful login authentication you might redirect to MenuPage.
On MenuPage.cs file you can easily access the static variable of App.cs file as :
public partial class MenuPage : MasterDetailPage
{
public MenuPage()
{
InitializeComponent();
string name = App.UserName;
}
}
Likewise you can access this Static variable across any pages of your portable project. This static variable will persist till you don't remove the app from the device's current running application tray list of android/ios.
Sample project of master detail page :
https://github.com/xamarin/xamarin-forms-samples/tree/master/Navigation
Sample project of Login flow :
https://github.com/xamarin/xamarin-forms-samples/tree/master/Navigation/LoginFlow
Here is something that you want to do:
on login you get the image and name to display on the drawer header and you store in a constant.
your Drawer page here
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MasterDetailsPageLogin.Views.DrawerPage"
Title="Menu"
BackgroundColor="#8999A6"
Padding="0,20,0,0">
<StackLayout Orientation="Vertical">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="10"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="80"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="5"/>
</Grid.RowDefinitions>
<BoxView Grid.ColumnSpan="3"
Grid.RowSpan="4"
BackgroundColor="#8999A6"/>
<Image
x:Name="img"
Grid.Column="1"
Grid.Row="1"
HorizontalOptions="Start"
VerticalOptions="End"
WidthRequest="75" HeightRequest="75"/>
<Label
x:Name="myName"
Grid.Column="1"
Grid.Row="2"/>
</Grid>
<ListView x:Name="listed" SeparatorColor="Transparent">
</ListView>
</StackLayout>
</ContentPage>
Code in your drawerpage.xaml.cs
public DrawerPage()
{
InitializeComponent();
string howILook = Constants.Image;
img.Source = new UriImageSource
{
Uri = new Uri(howILook),
CachingEnabled = true,
CacheValidity = new TimeSpan(1, 0, 0, 0) //Caching image for a day
};
myName.Text = "Welcome Mr. " + Constants.Username;
}
Here is a template I have created for the login logic and master details page.
https://github.com/ak47akshaykulkarni/MasterDetailsPageLogin
I would like to create a User Control which can embed free content.
I created a Dependency property for the content :
public sealed partial class MyUserControl : UserControl
{
public Border MyProperty
{
get { return (Border)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(Border), typeof(VisitList), new PropertyMetadata(new Border() { Height=300, Width=300 }));
...
}
So In my MainPage.xaml, I can use it with following code :
<MyUserControl>
<MyUserControl.MyProperty>
<Border x:Name="MyContent" Width="60" Height="60" Background="Pink">
... Whatever ...
</Border>
</MyUserControl.MyProperty>
</MyUserControl>
From this, I can't find what is the XAML syntax in the MyUserControl.xaml for declaring the placeholder that will be substituted by MyContent at runtime.
I tried with :
<UserControl ... >
....
<Grid ...>
<ContentPresenter Content="{TemplateBinding MyProperty}" />
</Grid>
</UserControl>
But, it crashes with message :
An exception of type 'Windows.UI.Xaml.Markup.XamlParseException' occurred in xXx.exe but was not handled in user code
WinRT information: Failed to create a 'Windows.UI.Xaml.DependencyProperty' from the text 'MyProperty'. [Line: 29 Position: 35]
(The Line: 29 Position:35 refers to Content="{TemplateBinding MyProperty}")
It sounds like you're mixing Templated Controls and UserControls. It's a bit complicated, but basically, TemplateBindings work when they're apart of the ContentTemplate of the control, as opposed to the Content itself (which is what I believe is happening here, based on the xaml you have shown).
Try changing your bindings in this way:
<UserControl x:Name="RootControl" ...>
....
<ContentControl Content="{Binding MyProperty, ElementName=RootControl}" />
....
</UserControl>
What this means is that you will need to have your UserControl implement INotifyPropertyChanged in case it needs to respond to changing Content.
I've created a custom control with a dependency property for databinding.
The binded value should then be displayed in a text box.
This binding works properly.
The problem occurs when I implement my custom control. The grid's data context is a simple view model which contains a String property for binding.
If I bind this property to a standard wpf controls text box everything works fine.
If I bind the property to my custom control nothing happens.
After some debugging I found out that SampleText is searched in CustomControl. Of course it doesn't exist there.
Why is my property searched in CustomControl and not taken from the DataContext as it happens in scenario 1.
<Window x:Class="SampleApplicatoin.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:SampleApplication"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.DataContext>
<controls:ViewModel/>
</Grid.DataContext>
<TextBox Text="{Binding SampleText}"/>
<controls:CustomControl TextBoxText="{Binding SampleText}"/>
</Grid>
</Window>
Below the XAML code of the custom control.
I use DataContext = Self to get the dependency property from code behind:
<UserControl x:Class="SampleApplication.CustomControl"
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="300" d:DesignWidth="300" DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<TextBox HorizontalAlignment="Left" Height="23" Margin="87,133,0,0" TextWrapping="Wrap" Text="{Binding TextBoxText}" VerticalAlignment="Top" Width="120"/>
</Grid>
</UserControl>
The xaml.cs file just contains the dependency property:
public partial class CustomControl : UserControl
{
public static readonly DependencyProperty TextBoxTextProperty = DependencyProperty.Register("TextBoxText", typeof (String), typeof (CustomControl), new PropertyMetadata(default(String)));
public CustomControl()
{
InitializeComponent();
}
public String TextBoxText
{
get { return (String) GetValue(TextBoxTextProperty); }
set { SetValue(TextBoxTextProperty, value); }
}
}
Thanks for any help on this. It really drives me crazy now.
EDIT:
I just came over two possible solutions:
Here the first (which works for me):
<!-- Give that child a name ... -->
<controls:ViewModel x:Name="viewModel"/>
<!-- ... and set it as ElementName -->
<controls:CustomControl TextBoxText="{Binding SampleText, ElementName=viewModel}"/>
The second one. This doesn't work in my case. I don't know why:
<controls:CustomControl TextBoxText="{Binding SampleText, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type controls:ViewModel}}}"/>
<!-- or -->
<controls:CustomControl TextBoxText="{Binding SampleText, RelativeSource={RelativeSource FindAncestor, AncestorType=controls:ViewModel}}"/>
I had a similar situation.
In my case, I fixed it with adding OnPropertyChanged in setter of property in ViewModel.