I have a user control that have a multi buttons and In the application i use this user control on multi windows ,but i want to Collapsed (shown/hidden) some buttons if the user select in the application a window 1 and show same button if the user select in the application a window 2
UserControl
<Grid x:Name="girdBtuWidow" >
<StackPanel Orientation="Horizontal">
<Button Content="add" x:Name="add" Visibility="{Binding window1_Loaded}" x:FieldModifier="public" Height="50" Width="100" Margin="0" Click="add_click" />
<Button Content="show history" x:Name="Personal" Height="50" Width="100" Margin="0" />
<Button Content="Show Customer" x:Name="Customer" Height="50" Width="100" Margin="0" />
</StackPanel>
</Grid>
how to set the property (Visibility) of button in the User Control from the application window ?
You don't need to use a Window_Loaded Event here.
You need to expose a Visibility property for each of your buttons in your UserControls.
In your UserControl add a binding to each button for the Visibility property:
Visibility="{Binding AddButtonVisibility}"
Visibility="{Binding ShowHistoryButtonVisibility}"
Visibility="{Binding ShowCustomerButtonVisibility}"
Make sure you add a DataContext to your UserControl, I generally use Self:
DataContext="{Binding RelativeSource={RelativeSource Self}}"
In your UserControl Code Behind add Dependency Properties for each of the Bindings above:
public Visibility AddButtonVisibility
{
get { return (Visibility)GetValue(AddButtonVisibilityProperty); }
set { SetValue(AddButtonVisibilityProperty, value); }
}
// Using a DependencyProperty as the backing store for AddButtonVisibility. This enables animation, styling, binding, etc...
public static readonly DependencyProperty AddButtonVisibilityProperty =
DependencyProperty.Register("AddButtonVisibility", typeof(Visibility), typeof(UserControl1), new PropertyMetadata(Visibility.Visible));
public Visibility ShowHistoryButtonVisibility
{
get { return (Visibility)GetValue(ShowHistoryButtonVisibilityProperty); }
set { SetValue(ShowHistoryButtonVisibilityProperty, value); }
}
// Using a DependencyProperty as the backing store for ShowHistoryButtonVisibility. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ShowHistoryButtonVisibilityProperty =
DependencyProperty.Register("ShowHistoryButtonVisibility", typeof(Visibility), typeof(UserControl1), new PropertyMetadata(Visibility.Visible));
public Visibility ShowCustomerButtonVisibility
{
get { return (Visibility)GetValue(ShowCustomerButtonVisibilityProperty); }
set { SetValue(ShowCustomerButtonVisibilityProperty, value); }
}
// Using a DependencyProperty as the backing store for ShowCustomerButtonVisibility. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ShowCustomerButtonVisibilityProperty =
DependencyProperty.Register("ShowCustomerButtonVisibility", typeof(Visibility), typeof(UserControl1), new PropertyMetadata(Visibility.Visible));
In Visual Studio, There is a code snippet shortcut for Dependency Properties - type propdp and hit tab twice.
Now, to use the properties you have just created put the Usercontrol onto the relevant window:
<local:UserControl1 AddButtonVisibility="Collapsed" />
local is the project namespaces' alias - defined at the top of your Window. You can just drag and drop the UserControl onto your window, and it will do this for you. (You may need to rebuild in order to see your UserControls in your Toolbox.
You should now see your control with the Add Button collapsed.
For completeness sake, here is the XAML side of things:
UserControl Xaml:
<UserControl x:Class="WpfApplication2.UserControl1"
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 x:Name="girdBtuWidow" >
<StackPanel Orientation="Horizontal">
<Button Content="Add" x:Name="add" Height="50" Width="100" Margin="0" Click="Add_Click" Visibility="{Binding AddButtonVisibility}"/>
<Button Content="Show History" x:Name="Personal" Height="50" Width="100" Margin="0" Click="ShowHistory_Click" Visibility="{Binding ShowHistoryButtonVisibility}" />
<Button Content="Show Customer" x:Name="Customer" Height="50" Width="100" Margin="0" Click="ShowCustomer_Click" Visibility="{Binding ShowCustomerButtonVisibility}"/>
</StackPanel>
</Grid>
Window1.Xaml:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication2" x:Class="WpfApplication2.Window1"
Title="Window1" Height="300" Width="308">
<Grid>
<local:UserControl1 HorizontalAlignment="Left" VerticalAlignment="Top" AddButtonVisibility="Collapsed" />
</Grid>
public static readonly DependencyProperty onBackVisibilityProperty =
DependencyProperty.Register("onBackVisibility", typeof(Visibility), typeof(MyToolBar), new PropertyMetadata(Visibility.Visible));
public Visibility onBackVisibility
{
get { return (Visibility)GetValue(onBackVisibilityProperty); }
set { SetValue(onBackVisibilityProperty, value); }
}
public static readonly DependencyProperty onBackVisibilityProperty =
DependencyProperty.Register("onBackVisibility", typeof(Visibility), typeof(MyToolBar), new PropertyMetadata(Visibility.Visible));
public Visibility onBackVisibility
{
get { return (Visibility)GetValue(onBackVisibilityProperty); }
set { SetValue(onBackVisibilityProperty, value); }
}
//After this goto xaml
Button Name="tbrBack"
ToolTip="{DynamicResource Back}"
VerticalAlignment="Center"
VerticalContentAlignment="Center"
Click="tbrBack_Click"
Visibility="{Binding onBackVisibility ,ElementName = usercontrol}
Related
I am trying get a value from a property but isn't working I always get a null value.
string imageNormal;
public static readonly DependencyProperty ImageNormalProperty =
DependencyProperty.Register("ImageNormal", typeof(string), typeof(MainWindow));
public string ImageNormal
{
get { return (string)GetValue(ImageNormalProperty); }
set { SetValue(ImageNormalProperty, value); }
}
public ButtonImageStyle()
{
InitializeComponent();
DataContext = this;
Console.WriteLine("Path: " + ImageNormal);
}
Xaml ButtonImageStyle.xaml:
<Image Source="{Binding ImageNormal}" Stretch="None" HorizontalAlignment="Center" VerticalAlignment="Center" />
Xaml MainWindow.xaml:
<local:ButtonImageStyle HorizontalAlignment="Left" Height="60" VerticalAlignment="Top" Width="88" ImageNormal="C:/Users/Xafi/Desktop/add.png"/>
I always obtain next output:
Path:
since your ImageSource is have to be binded to it's parent DependencyProperty (which is defined to your code behind), you have to define your binding to be rlative to your UserControl (let's name it This). Thus please try to change your xaml in the next way:
Xaml code
<UserControl x:Class="SomeBindingExampleSOHelpAttempt.ButtonImageStyle"
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" x:Name="This">
<Grid>
<Image Source="{Binding ElementName=This, Path=ImageNormal, UpdateSourceTrigger=PropertyChanged}"
Stretch="None" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid></UserControl>
Here you can find an additional perfect answer.
Regards.
I have a user control like so:
<Grid>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding NameC}" Width="100" />
<TextBlock Text="{Binding Filename}" />
</StackPanel>
</Grid>
with DP in code behind:
public TestUc()
{
InitializeComponent();
DataContext = this;
}
public static readonly DependencyProperty NameCProperty = DependencyProperty.Register(
"NameC", typeof(string), typeof(TestUc), new PropertyMetadata(default(string)));
public string NameC
{
get { return (string) GetValue(NameCProperty); }
set { SetValue(NameCProperty, value); }
}
public static readonly DependencyProperty FilenameProperty = DependencyProperty.Register(
"Filename", typeof (string), typeof (TestUc), new PropertyMetadata(default(string)));
public string Filename
{
get { return (string) GetValue(FilenameProperty); }
set { SetValue(FilenameProperty, value); }
}
Now, when using it in a window,
this works fine:
<Window x:Class="TestDpOnUc.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:uc="clr-namespace:TestDpOnUc"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<uc:TestUc NameC="name is xxx" Filename="This is filename" />
</Grid>
But This does not:
<Window x:Class="TestDpOnUc.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:uc="clr-namespace:TestDpOnUc"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<uc:TestUc NameC="{Binding Name}" Filename="{Binding FileName}" />
</Grid>
public MainWindow()
{
InitializeComponent();
DataContext = this;
Name = "name is nafsafd";
FileName = "lkjsfdalkf";
}
private string _Name;
public string Name
{
get { return _Name; }
set
{
_Name = value;
OnPropertyChanged();
}
}
private string _FileName;
public string FileName
{
get { return _FileName; }
set
{
_FileName = value;
OnPropertyChanged();
}
}
Can someone please explain why? Why is the datacontext of the user control not automatically set to the parent - the main window?
It's because of this line DataContext = this in UserControl constructor. You set DataContext to your user control which affects default binding context for TestUc and all children, including <uc:TestUc ... />. So at the moment
<uc:TestUc NameC="{Binding Name}" Filename="{Binding FileName}" />
will look for Name and FileName properties inside UserControl. You need to remove that line but that will break bindings within the user control.
<TextBlock Text="{Binding NameC}" Width="100" />
<TextBlock Text="{Binding Filename}" />
Will look for NameC and Filename in MainWindow. Solution to that is to change binding context, per binding, via either RelativeSource or ElementName binding inside UserControl
<UserControl ... x:Name="myUserControl">
<Grid>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding ElementName=myUserControl, Path=NameC}" Width="100" />
<TextBlock Text="{Binding ElementName=myUserControl, Path=Filename}" />
</StackPanel>
</Grid>
</UserControl>
When creating a UserControl with DependencyProperties you have to bind your DP's within your UserControl with ElementName- or RelativeSource Binding to your Controls in your UserControl
<TextBlock Text="{Binding ElementName=myUserControl, Path=NameC}" Width="100" />
and you never set the DataContext.
DataContext = this; <-- do not do that within your UserControl
When you wanna use your UserControl you put it in your View and bind the Properties of your actual DataContext/Viewmodel to the DependencyProperties of the UserControl.
<uc:TestUc NameC="{Binding Name}" Filename="{Binding FileName}" />
Whe you are doing <uc:TestUc NameC="{Binding Name}" Filename="{Binding FileName}" /> its not looking at MainWindow's data context instead at your UserControl's data context.
So you might want to search for the right element and bind it. Below is one way to do it using ElementName by giving a name to Window like MainWindowName. Or you can also use relative source to search for its ancestor.
<Window x:Class="TestDpOnUc.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:uc="clr-namespace:TestDpOnUc"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
x:Name="MainWindowName">
<Grid>
<uc:TestUc NameC="{Binding Element=MainWindowName, Path=DataContext.Name}" Filename="{Binding Element=MainWindowName, Path=DataContext.FileName}" />
</Grid>
main window
<TextBox x:Name="fbSearchBox" Margin="69,10,298,11" TextWrapping="Wrap" BorderBrush=" x:Null}"/>
<local:FacebookAutoComplete "want to set text from here of fbSearchBox" />
user control
<UserControl x:Class="ZuneWithCtrls.Pages.Facebook.Home.FacebookAutoComplete"
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" Width="431" Height="49"
x:Name="uc">
<TextBlock x:Name="txtDynamicText"/>
</UserControl>
want to show text in txtdynamicText when type from fbSearchBox.. Plz help
You need some property in user control you can bind to.
Add a dependency property to your user control:
public static readonly DependencyProperty DynamicTextProperty =
DependencyProperty.Register(
"DynamicText",
typeof(string),
typeof(FacebookAutoComplete),
new FrameworkPropertyMetadata(null));
public string DynamicText
{
get { return (string)GetValue(DynamicTextProperty); }
set { SetValue(DynamicTextProperty, value); }
}
Bind a nested control inside user control to this dependency property:
<TextBlock x:Name="txtDynamicText"
Text="{Binding Path=DynamicText, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"/>
Now you can bind FacebookAutoComplete.DynamicText to the TextBox from MainWindow:
<local:FacebookAutoComplete DynamicText="{Binding Text, ElementName=fbSearchBox, UpdateSourceTrigger=PropertyChanged}"/>
I've a ObservableCollection's list that receives data from the database, and i put this data in my grid, by data binding.
So, i've a user control that appears when i click in a item of this grid. I want that a text box of my user control, show the selected item of my grid.
I've tried this using data binding, but the textbox not shows the selected item.. is it possible ?
grid code:
<FlexGrid:C1FlexGrid
x:Name="grid" ItemsSource="{Binding list3, Mode=TwoWay}"
AutoGenerateColumns="False"
HorizontalAlignment="Left" Height="431" Margin="10,147,0,0" VerticalAlignment="Top" Width="1152" SelectionMode="Row" KeepCurrentVisible="True" Tapped="grid_Tapped" >
<FlexGrid:C1FlexGrid.DataContext>
<local:Controller/>
</FlexGrid:C1FlexGrid.DataContext>
<FlexGrid:C1FlexGrid.Columns>
<FlexGrid:Column Binding="{Binding describe}" Header="Describes" Width="800" />
<FlexGrid:Column Binding="{Binding describeNote}" Header="Describes Notes" Width="300" />
</FlexGrid:C1FlexGrid.Columns>
</FlexGrid:C1FlexGrid>
User Control code:
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Binding"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:FlexGrid="using:C1.Xaml.FlexGrid"
x:Class="Binding.popNotas"
mc:Ignorable="d" Height="281.925" Width="656.03">
<Grid>
<TextBox x:Name="txt2" Text="{Binding SelectedItem.describe, ElementName=grid, Mode=TwoWay}" Height="38" Margin="140,5,141,0" TextWrapping="Wrap" VerticalAlignment="Top">
</TextBox>
</Grid>
cs code
public class Controller : Common.BindableBase
{
//DAOS
public TesteDao dao { get; set; }
private ObservableCollection<ClPasso> _list3 = new ObservableCollection<ClPasso>();
public ObservableCollection<ClPasso> list3
{
get { return _list3; }
set { this.SetProperty(ref this._list3, value); }
}
public Controller()
{
OnNavigatedTo();
}
protected async void OnNavigatedTo()
{
await InitializeDatabase();
list3 = await createlist3();
}
private async Task InitializeDatabase()
{
string datbasePath = Windows.Storage.ApplicationData.Current.LocalFolder.Path + "\\bd_example.db";
DataBase database = new DataBase (datbasePath);
await database.initialize();
dao = new TesteDao(database);
}
public async Task<ObservableCollection<ClPasso>> createlist3()
{
return await dao.joinListAsync(123, "924be4cc-16db-40c2-b342-d6c1fccbec86");
}
}
Help!
Thanks!!!
i've solved my question..
So, i created a DependencyProperty on code behind of my User Control, named selection, and i put this in Text of my text box.. after, when i will using my user control, in my main page, i passed the value in for porperty..
Like this:
User Control
public sealed partial class UCNotes : UserControl
{
public string selection
{
get { return (string)GetValue(selectionProperty); }
set { SetValue(selectionProperty, value); }
}
public static readonly DependencyProperty selecionadoProperty =
DependencyProperty.Register("selection", typeof(string), typeof(UCNotes), new PropertyMetadata(null));
User Control XAML
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Test"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:FlexGrid="using:C1.Xaml.FlexGrid"
x:Class="Fiscalizacao.UCNotes"
mc:Ignorable="d"
d:DesignHeight="327.068" Width="799.248">
<Grid Margin="10,0,10,10" Background="#FFB2B2B2" Height="303" VerticalAlignment="Bottom">
<TextBox x:Name="txtSelection" Text="{Binding selection}" Height="38" Margin="153,75,153,0" TextWrapping="Wrap" VerticalAlignment="Top" BorderBrush="Black"/>
Main Page XAML
<FlexGrid:C1FlexGrid
x:Name="questionsGrid"
HorizontalAlignment="Left" Height="417" Margin="31,181,0,0" VerticalAlignment="Top" Width="1306"
AutoGenerateColumns="False" KeepCurrentVisible="True"
SelectionMode="Row" ItemsSource="{Binding list, Mode=TwoWay}">
<FlexGrid:C1FlexGrid.Columns>
<FlexGrid:Column Binding="{Binding describes}" Header="Descrição" Width="900" />
<FlexGrid:Column Binding="{Binding descibesNotes}" Header="Nota" Width="*" />
</FlexGrid:C1FlexGrid.Columns>
</FlexGrid:C1FlexGrid>
<Popup x:Name="popNotes" IsLightDismissEnabled="True" IsOpen="False" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" Margin="0,0,700,300" >
<local:UCNotes selection="{Binding SelectedItem.describes, ElementName=questionsGrid" />
</Popup>
I want to use the ToggleSwitch control of the WPF Spark project
So I created a UserControl which contains a ToggleSwitch control and configures it (color, size, etc).
<UserControl x:Class="WpfControls.ToggleSwitch.MyToggleSwitchControl"
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:toggleSwitch="clr-namespace:WpfControls.ToggleSwitch"
d:DesignHeight="300"
d:DesignWidth="300"
mc:Ignorable="d">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/WpfControls;component/ToggleSwitch/ToggleSwitch.Generic.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<Grid>
<toggleSwitch:ToggleSwitch x:Name="Toggle"
Width="54"
Height="21"
Margin="0"
Background="Black"
BorderThickness="2"
CheckedForeground="White"
CheckedText="Yes"
CheckedToolTip=""
CornerRadius="10"
FontFamily="Tahoma"
FontSize="10"
FontWeight="Normal"
IsCheckedLeft="False"
Padding="0"
ThumbBorderThickness="2"
ThumbCornerRadius="21"
ThumbGlowColor="Gray"
ThumbShineCornerRadius="20,20,0,0"
ThumbWidth="35"
UncheckedForeground="Black"
UncheckedText="No"
UncheckedToolTip="No">
</toggleSwitch:ToggleSwitch>
</Grid>
</UserControl>
The ToggleSwitch is a CustomControl which overrides the standard WPF ToggleButton.
Now I want to use the ToggleButton property IsChecked in my XAML for Binding.
<toggleSwitch:MyToggleSwitchControl IsChecked="{Binding IsChecked}" />
How can I achieve that?
Create in code-behind DependencyProperty:
public bool IsToggleChecked
{
get { return (bool)GetValue(IsToggleCheckedProperty); }
set { SetValue(IsToggleCheckedProperty, value); }
}
public static readonly DependencyProperty IsToggleCheckedProperty =
DependencyProperty.Register("IsToggleChecked", typeof(bool), typeof(MyToggleSwitchControl), new PropertyMetadata(false));
and bind it to IsChecked property of your ToggleSwitch:
<toggleSwitch:ToggleSwitch IsChecked="{Binding RelativeSource={RelativeSource AncestorLevel=1,AncestorType=UserControl,Mode=FindAncestor}, Path=IsToggleChecked}"
After doing this you'll be able to do:
<toggleSwitch:MyToggleSwitchControl IsToggleChecked="{Binding IsChecked}" />
You could use an dependency property.
In your custom control add a dependency property like this:
public static readonly DependencyProperty IsCheckedProperty =
DependencyProperty.Register("IsChecked", typeof(bool),
typeof(MyToggleSwitchControl), null);
// .NET Property wrapper
public bool IsChecked
{
get
{
return (bool)GetValue(IsCheckedProperty);
}
set { SetValue(IsCheckedProperty, value); }
}