wp7学习笔记

时间:2023-03-08 17:36:49

1.xap:最终是压缩包;最终部署有系统控制,防止流亡软件;放到固有位置productid;有的文件放在.dll中或直接放入目录下;控制有生成操作:content,内容,content效率更高不用从.dll文件解压出来;resource则放入.dll中;

2.xaml是编译到dll资源中去,然后允许通过loadcomponent加载xaml文件,通过findName获得控件实例;

3.布局:

<Canvas>绝对位置;Canvas.Left="100" Canvas.Top="300"来调整位置;

<StackPanel Orientation="Horizontal">:默认垂直;

4.Canvas.SetTop(a, Canvas.GetTop(a) + 100);Canvas

5.  TextBox t1 = new TextBox();

t1.Text = "n" + i.ToString();

sp1.Children.Add(t1);

7. TextBox tt = this.FindName("n2") as TextBox;

8. <TextBlock.Foreground>

<SolidColorBrush Color="blue" ></SolidColorBrush>

</TextBlock.Foreground>

9.渐变:

<TextBlock.Foreground>

<LinearGradientBrush StartPoint="0,1" EndPoint="1,1" >(渐变方向表示从上到下)

<GradientStop Offset="0.2" Color="Blue"></GradientStop>

<GradientStop Offset="0.9" Color="Yellow"></GradientStop>

</LinearGradientBrush>

10.(从中心向外面扩散)

<TextBlock.Foreground>

<RadialGradientBrush >

<GradientStop Offset="0.1" Color="Blue"></GradientStop>

<GradientStop Offset="0.6" Color="Yellow"></GradientStop>

</RadialGradientBrush>

</TextBlock.Foreground>

(stroke)边框颜色;thickness:宽度;

11.   <Rectangle Width="100" Height="100" Stroke="Green" StrokeThickness="10">

</Rectangle>

12.

<GradientStop Offset="0.3" Color="Blue"></GradientStop>

<GradientStop Offset="0.5" Color="Yellow"></GradientStop>

<GradientStop Offset="0.8" Color="red"></GradientStop>

----表示:(0.3以内为蓝色;0.3-o.5由蓝色变为黄色;0.5到0.8由换色为红色);0.8以外为红色;

--------- <TextBlock.Foreground>

<ImageBrush ImageSource="Img/010.png"></ImageBrush>

</TextBlock.Foreground>(用图片渲染;)

------------旋转:(angel角度;rotate:旋转)angle>0顺时针;<0逆时针;

<StackPanel>

<Button Content="sdfsfs" Width="200" Height="100">

<Button.RenderTransform>

<RotateTransform Angle="-10"></RotateTransform>

</Button.RenderTransform>

</Button>

</StackPanel>

----------- <RotateTransform Angle="20" CenterX="100" CenterY="500"></RotateTransform>:默认0,0通过centerx,center来设定旋转中心;

---- <ScaleTransform ScaleX="0.4"></ScaleTransform>缩放横放;沿x轴和纵轴;

-------   <SkewTransform AngleX="" AngleY="50"></SkewTransform>歪斜,沿x轴,沿y轴;anglex:x轴不变;

------如果控件是从frameElement继承过来可以。出name;不过不是必须是x:name;

---------------

using System.Windows.Threading;//时间命名控件

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)

{

DispatcherTimer d = new DispatcherTimer();//定时器;(解决多线程问题)

d.Interval = TimeSpan.FromSeconds(1);

d.Tick += new EventHandler(d_Tick);

d.Start();

}

void d_Tick(object sender, EventArgs e)

{

sd.AngleY += 10;

}

}

----------------样式:(指定name后 Style="{ StaticResource aa }"来引用样式)base on 指的是继承样式;

<phone:PhoneApplicationPage.Resources>

<Style TargetType="Button">

<Setter Property="Background" Value="Yellow">

</Setter>

</Style>

<Style TargetType="Button" x:Name="aa">

<Setter Property="Background" Value="Red">

</Setter>

</Style>

<Style TargetType="Button" BasedOn="{StaticResource aa}" x:Name="ba">

<Setter Property="FontSize"  Value="88">

</Setter>

</Style>

</phone:PhoneApplicationPage.Resources>

----------样式表:新建xml文件重新命名为xaml;

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<Style TargetType="Button">

<Setter Property="Background" Value="Yellow">

</Setter>

</Style>

<Style TargetType="Button" x:Key="aa">

<Setter Property="Background" Value="Red">

</Setter>

</Style>

<Style TargetType="Button" BasedOn="{StaticResource aa}" x:Key="ba">

<Setter Property="FontSize"  Value="88">

</Setter>

</Style>

</ResourceDictionary>

---xaml文件引用样式:

<phone:PhoneApplicationPage.Resources>

<ResourceDictionary Source="style.xaml"></ResourceDictionary>

</phone:PhoneApplicationPage.Resources>

--------如果只有一个样式表,比较简单的话;

直接放入app.xaml的resource中更好;

所有页面都自动引用;

----------------动态修改image图片;

using System.Windows.Media.Imaging;//image的命名空进啊

bb.Source = new BitmapImage(new Uri("Img/1.jpg",UriKind.Relative));//相对的路径

------------------换肤功能:

添加样式文件;xaml中不能定义样式

<phone:PhoneApplicationPage.Resources>

<!--<ResourceDictionary Source="style1.xaml">

</ResourceDictionary>-->

</phone:PhoneApplicationPage.Resources>

2.后台代码:

private void a_Click(object sender, RoutedEventArgs e)

{

ResourceDictionary rd = new ResourceDictionary();

rd.Source = new Uri("/PhoneApp1;component/skin/style2.xaml", UriKind.Relative);

//|路径固定写法(phoneapp1:程序及名称)component/路径|

AppStyle(rd);

}

private static void AppStyle(ResourceDictionary rd)

{

App.Current.Resources.MergedDictionaries.Clear();

App.Current.Resources.MergedDictionaries.Add(rd);

}

private void b_Click(object sender, RoutedEventArgs e)

{   //动态将样式文件添加到app.xaml中去;

ResourceDictionary rd = new ResourceDictionary();

rd.Source = new Uri("/PhoneApp1;component/skin/style1.xaml", UriKind.Relative);

AppStyle(rd);

}

-----------多语言一样:添加 xmlns:sys="clr-namespace:System;assembly=mscorlib"

--------------通过模板改变整体外观;

<Button Content="点击" Click="Button_Click" Height="110" Width="126">

<Button.Template>

<ControlTemplate>

<Ellipse Width="100" Height="100" Fill="Red">

</Ellipse>

</ControlTemplate>

</Button.Template>

</Button>

-------------------

<phone:PhoneApplicationPage.Resources>

<ControlTemplate x:Name="a">

<Grid>

<Ellipse Width="100" Height="100" Fill="Red">

</Ellipse>

<TextBlock Text="sfs" VerticalAlignment="Center" HorizontalAlignment="Center"></TextBlock>

</Grid>

</ControlTemplate>

</phone:PhoneApplicationPage.Resources>

----

<Button Template="{ StaticResource a}"></Button>

---(这样就可以保持和button按钮的值同步;)

<ControlTemplate x:Name="a">

<Grid>

<Ellipse Width="100" Height="100" Fill="Red">

</Ellipse>

<TextBlock Text="{TemplateBinding Button.Content}" VerticalAlignment="Center" HorizontalAlignment="Center"></TextBlock>

</Grid>

</ControlTemplate>

---------绑定控件的content属性;所以这样就可以同步conent所有形式,比如在button按钮中放图片也可以;

<Grid>

<Ellipse Width="100" Height="100" Fill="Red">

</Ellipse>

<!--<TextBlock Text="{TemplateBinding Button.Content}" VerticalAlignment="Center" HorizontalAlignment="Center"></TextBlock>-->

<ContentControl Content="{TemplateBinding Button.Content}"></ContentControl>

</Grid>

------------控件绑定;

<Slider Name="s1" Value="{Binding Text,ElementName=aa,Mode=TwoWay}">

----------------获取资源文件的类;相当于控制反转;

Person p1 = (Person)this.Resources["cB"];cb是键值;

-----------------页面数据绑定(当页面需要随着model值变化)

(1)定义person类;(这两种都可以,建议是第二种)

(2)amespace PhoneApp1.bangding

{

//public class Person : INotifyPropertyChanged

//{

//    #region INotifyPropertyChanged 成员

//    public event PropertyChangedEventHandler PropertyChanged;

//    #endregion

//    private string name;

//    public string Name

//    {

//        get { return name; }

//        set

//        {

//            name = value;

//            if (PropertyChanged != null)

//            {

//                PropertyChanged(this,new PropertyChangedEventArgs("Name"));name指的是属性name

//            }

//        }

//    }

//}

public class Person : DependencyObject

{

//静态的,DependeycyPerty,属性名+property=属性名,属性类型,所属类,null);

public static DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(Person), null);

public string Name

{

get

{

return GetValue(NameProperty) as string;

}

set

{

SetValue(NameProperty, value);

}

}

//自动生成(插入外侧代码,nf30,)

public double MyProperty

{

get { return (double)GetValue(MyPropertyProperty); }

set { SetValue(MyPropertyProperty, value); }

}

// Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...

public static readonly DependencyProperty MyPropertyProperty =

DependencyProperty.Register("MyProperty", typeof(double), typeof(ownerclass), new UIPropertyMetadata(0));

}

}

(3)引入类

xmlns:my="clr-namespace:PhoneApp1.bangding"

(4)放到资源中;

<phone:PhoneApplicationPage.Resources>

<my:Person Name="cA" x:Key="cB"></my:Person>

</phone:PhoneApplicationPage.Resources>

(5)引用资源:

<TextBox Name="txtName" Text="{Binding Name}" DataContext="{StaticResource cB}">

</TextBox>

--------------------------------------------- DataContext="{StaticResource cB}上下文可以设定到父节点上;

-----------绑定listbox有两种形式:

InitializeComponent();

List<Person> list = new List<Person>();

list.Add(new Person {Name="郭泽峰",Age=22});

list.Add(new Person { Name = "张三", Age = 22 });

list.Add(new Person { Name = "李四", Age = 24 });

//ltbData.ItemsSource = list;(1)

ltbData.DataContext = list;(2)种类;这种需要添加;ItemsSource="{Binding}"

------------匿名委托:

Thread t = new Thread(() => {

this.Dispatcher.BeginInvoke(() => {

list.Add(new Person { Name = "郭泽峰", Age = 22 });

});

Thread.Sleep(1000);

this.Dispatcher.BeginInvoke(() =>

{

list.Add(new Person { Name = "郭泽峰", Age = 22 });

});

t.start();

要想使控件随数据源动态源集合变化,必须使用其他集合:

using System.Collections.ObjectModel;

private ObservableCollection<Person> list = new ObservableCollection<Person>();

------------知识点:

silverlight不能再非UI线程中访问UI线程控件,而机场自DependencyObject的类都是UI线程东西,并且访问

要使用:this.Dispatcher.BeginInvoke(()=>{ ....});

要要求集合的数据变化反应到ui上,必须实现InotifyCollectionChange接口;一般使用系统预定义的ObservableCollection类;

------------------------------------------------------------------------------------------------------------------

MVVM是Model-View-ViewModel的简写。

-------------绑定其他的事件:

(1)添加对程序集的引用

(2)xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

(3)<TextBlock  Foreground="Yellow" Text="点击事件(其它事件绑定案例)">

<i:Interaction.Triggers>

<i:EventTrigger EventName="Tap">

<i:InvokeCommandAction Command="{Binding AddCmd}" CommandParameter="{Binding}">

</i:InvokeCommandAction>

</i:EventTrigger>

</i:Interaction.Triggers>

</TextBlock>

(4)后台代码不变;

---------------------数据转换

(1)

public int Sex

{

get { return (int)GetValue(SexProperty); }

set { SetValue(SexProperty, value); }

}

public static readonly DependencyProperty SexProperty =

DependencyProperty.Register("Sex", typeof(int), typeof(Person), null);

(2)

public class Conv:IValueConverter

{

#region IValueConverter 成员

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

{

//value为实体的属性值

string a = value.ToString();

if (a == "1")

return "女";

else

return "男";

}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

{

if (value.ToString() == "男")

return 0;

else

return 1;

}

#endregion

}

(3)

<StackPanel>

<ListBox Name="Li" ItemsSource="{Binding}">

<ListBox.ItemTemplate>

<DataTemplate>

<TextBlock Text="{Binding Sex,Mode=TwoWay,Converter={StaticResource Con}}">

</TextBlock>

</DataTemplate>

</ListBox.ItemTemplate>

</ListBox>

------------------------------动画:

<phone:PhoneApplicationPage.Resources>

<Storyboard x:Name="st">

<DoubleAnimation Storyboard.TargetName="aa" Storyboard.TargetProperty="Angle"

From="0" To="360" AutoReverse="True" RepeatBehavior="Forever">

</DoubleAnimation>

</Storyboard>

</phone:PhoneApplicationPage.Resources>

---------------------------------------------------

<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">

<Image Source="../捕获.PNG" Width="100" Height="100">

<Image.RenderTransform>

<RotateTransform CenterX="0" CenterY="0" Angle="30" x:Name="aa">

</RotateTransform>

</Image.RenderTransform>

</Image>

</StackPanel>

-----------------------------------------------------windowsphone:内核是底层:windowsCE;windowce-->windows mobel;

安卓:linux;

ios:unix;

windows phone和windows mobel是windows CE的两个分支;

------

配置文件中<Capabilities>表示注册需要操作设备的权限;

---------------控制方向;

SupportedOrientations="PortraitOrLandscape"  Orientation="Portrait"

会触发一个事件(前提SupportedOrientations="PortraitOrLandscape"才能出发)

protected override void OnOrientationChanged(OrientationChangedEventArgs e)重写这个函数即可;

this.SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;//这只方向;

设置按钮的显隐;

----------------------applicationbar最多放按钮放了4个,条目放50个;

图标大小和格式都有要求必须是png,且是48*48;开机画面图片名字不变;图片必须生成为内容,而不是资源,这点必须注意;

--------------applicationbar中的按钮和菜单是没法通过findName找到的;所以;ApplicationBar不是名字而是标签的名字;

ApplicationBarIconButton bb = ApplicationBar.Buttons[1] as ApplicationBarIconButton;

bb.IconUri = new Uri("/Img/appbar.cancel.rest.png",UriKind.Relative);

-------sip:softinputPanel;软件盘;

//通过这段代码可以找出所有类型 ;

InputScopeNameValue.Number

//前台代码:

<TextBox Name="aa" InputScope="AddressCity"></TextBox>

----------------wp7:Coding4Fun.Toolkit.Controls;应用;

//ToastPrompt tp = new ToastPrompt();

//tp.Message = "你大爷的";

//tp.Show();

//messageprompt是一个异步的避免阻塞UI线程;

MessagePrompt mp = new MessagePrompt();

mp.IsCancelVisible = true;

mp.Title = "确认删除吗";

mp.Message = "哈哈哈";

mp.Completed += new EventHandler<PopUpEventArgs<string, PopUpResult>>(mp_Completed);

mp.Show();

//MessageBoxResult result = MessageBox.Show("哈哈", "提示", MessageBoxButton.OKCancel);

//if (result == MessageBoxResult.OK)

//{

//最好不要再loaded内放入执行太长时间的代码,比如扫描文件,因为10秒钟后线程就会被干掉;

//    MessageBox.Show("选择了ok");

//}

//else

//{

//    MessageBox.Show("选择了NO");

//}

----------------------当listpiker项目比较多时items比较多时,就会报错;

------------在项目中一定要存在Toolkit.Content这个文件夹;因为一些控件会自动到这个文件家中去找相应图片,比如说确定,和取消按钮;

---WrapPanel:一次排列;实时上我们可以不用grid控件;

----菜单控件;需要长按textbox可以弹出;

<TextBox Name="tt">

<tk:ContextMenuService.ContextMenu>

<tk:ContextMenu>

<tk:MenuItem Header="菜单一"></tk:MenuItem>

<tk:MenuItem Header="菜单二"></tk:MenuItem>

<tk:MenuItem Header="菜单三"></tk:MenuItem>

<tk:MenuItem Header="菜单四"></tk:MenuItem>

</tk:ContextMenu>

</tk:ContextMenuService.ContextMenu>

</TextBox>

--------- 动态图片;

<tk:HubTile Message="哈哈" Notification="你大爷" Source="../Img/1.jpg">

</tk:HubTile>

------using System.Windows.Controls.Primitives;(独立于页面)

Popup pp = new Popup();

Button btn = new Button();

btn.Content = "你大爷的";

pp.Child = btn;

pp.IsOpen = true;

------选项卡尽量不要与applicationBar一起使用;需要添加microsoft.phone.controls;

<con:Pivot>

<con:PivotItem Header="标题一">

<StackPanel>

<CheckBox Content="哈哈哈"></CheckBox>

<CheckBox Content="哈哈哈"></CheckBox>

<CheckBox Content="哈哈哈"></CheckBox>

</StackPanel>

</con:PivotItem>

<con:PivotItem Header="标题二">

<StackPanel>

<CheckBox Content="哈哈哈"></CheckBox>

<CheckBox Content="哈哈哈"></CheckBox>

<CheckBox Content="哈哈哈"></CheckBox>

</StackPanel>

</con:PivotItem>

<con:PivotItem Header="标题三">

<StackPanel>

<CheckBox Content="哈哈哈"></CheckBox>

<CheckBox Content="哈哈哈"></CheckBox>

<CheckBox Content="哈哈哈"></CheckBox>

</StackPanel>

</con:PivotItem>

</con:Pivot>

---------------------独立存储

每个程序只能读取自己的文件夹,其它的程序不能读取;没有权限这样就防止了病毒;

需要引入命名控件

using System.IO.IsolatedStorage;//命名控件

(1)

using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())

{

using (Stream str = file.CreateFile("a.txt"))

{

using (StreamWriter sw = new StreamWriter(str))

{

sw.WriteLine(txtName.Text);

}

}

}

//IsolatedStorageFileStream istr = new IsolatedStorageFileStream("Hellow\\a.txt", FileMode.OpenOrCreate, file);

(2)

IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();

if (file.FileExists("a.txt"))

using (Stream str = file.OpenFile("a.txt",FileMode.Open))

{

using (StreamReader sr=new StreamReader(str))

{

string line = sr.ReadLine();

txtName.Text = line;

}

}

-----------------------

IsolatedStorageSettings.ApplicationSettings["Name"] = txtName.Text;

IsolatedStorageSettings.ApplicationSettings.Save();//别忘了保存

----

if (IsolatedStorageSettings.ApplicationSettings.Contains("Name"))

{

txtName.Text = IsolatedStorageSettings.ApplicationSettings["Name"].ToString();

}

------------------跳转页面需要从根目录开始

NavigationService.Navigate(new Uri("/content/tiao2.xaml", UriKind.Relative));

NavigationService.Navigate(new Uri("/content/tiao2.xaml?name=guozefeng", UriKind.Relative));

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)

{

base.OnNavigatedTo(e);

if (NavigationContext.QueryString["name"] != null)

{

string name = NavigationContext.QueryString["name"].ToString();

MessageBox.Show(name);

}

}

----------------还有一种就是静态属性了;(如果比较数据类型复杂的话)

if (NavigationService.CanGoForward)

{

NavigationService.GoForward();

}

---------------已经退出触发的时间

protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)

{

base.OnNavigatedFrom(e);

}

//将要退出;

protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)

{

base.OnNavigatingFrom(e);

messagebox.show("将要离开吗")==OK;

e.cancel=false;//取消离开;

}

//按返回键时。OnBackKeyPress

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)

{

base.OnBackKeyPress(e);

}

-------------执行顺序:

InitializeComponent();--->OnNavigatedTo--->最后才是page_loaded;

if (e.NavigationMode == System.Windows.Navigation.NavigationMode.New)

{

//判断是不是首次加载,是的话,好初始化;避免了重复加载初始化,提高性能;

//尽量将初始化的东西加载到onNavigatedTo中;

}

--------------------文件为内容文件;

private void du1_Click(object sender, RoutedEventArgs e)

{

StreamResourceInfo si = Application.GetResourceStream(new Uri("content/log.txt",UriKind.Relative));

using (StreamReader sr = new StreamReader(si.Stream))

{

string str = sr.ReadToEnd();

MessageBox.Show(str);

}

}

-----文件为资源;

private void du2_Click(object sender, RoutedEventArgs e)

{

StreamResourceInfo si = Application.GetResourceStream(new Uri("/PhoneApp1;component/content/log1.txt",UriKind.RelativeOrAbsolute));

using (StreamReader sr = new StreamReader(si.Stream))

{

string str = sr.ReadToEnd();

MessageBox.Show(str);

}

}

-------翻页效果:

在主页面开始:

<toolkit:TransitionService.NavigationInTransition>

<toolkit:NavigationInTransition>

<toolkit:NavigationInTransition.Backward>

<toolkit:TurnstileTransition Mode="BackwardIn"/>

</toolkit:NavigationInTransition.Backward>

<toolkit:NavigationInTransition.Forward>

<toolkit:TurnstileTransition Mode="ForwardIn"/>

</toolkit:NavigationInTransition.Forward>

</toolkit:NavigationInTransition>

</toolkit:TransitionService.NavigationInTransition>

<toolkit:TransitionService.NavigationOutTransition>

<toolkit:NavigationOutTransition>

<toolkit:NavigationOutTransition.Backward>

<toolkit:TurnstileTransition Mode="BackwardOut"/>

</toolkit:NavigationOutTransition.Backward>

<toolkit:NavigationOutTransition.Forward>

<toolkit:TurnstileTransition Mode="ForwardOut"/>

</toolkit:NavigationOutTransition.Forward>

</toolkit:NavigationOutTransition>

</toolkit:TransitionService.NavigationOutTransition>

----(2)改app.xaml;

// 创建框架但先不将它设置为 RootVisual;这允许初始

// 屏幕保持活动状态,直到准备呈现应用程序时。

//RootFrame = new PhoneApplicationFrame();

RootFrame = new TransitionFrame();

--------发送短信:

using Microsoft.Phone.Tasks;//引用;

SmsComposeTask sm = new SmsComposeTask();

sm.To = "10086";

sm.Body = "你好,你大爷的";

sm.Show();