小试用户控件

window phone 有一个叫User Control 的东西。可以创建自己定义的控件。今天特意来试下。
首先。在项目上右键--添加--新建项。
<WP7>小试用户控件_第1张图片
命名这个控件为forecastInfo。
在xaml的layout里面添加代码:
<Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Column="0" Grid.Row="0"
                   x:Name="day" HorizontalAlignment="Center"
                   VerticalAlignment="Top" Text="星期八"
                   FontSize="40"/>
        <TextBlock Grid.Column="0" Grid.Row="1"
                   x:Name="whether" HorizontalAlignment="Center"
                   VerticalAlignment="Top" FontSize="40"
                   Text="7℃~9℃"/>
        <Image x:Name="WImg" Grid.Column="1" Grid.Row="0"
               Grid.RowSpan="2" VerticalAlignment="Center"
               HorizontalAlignment="Left"/>

显示效果:
<WP7>小试用户控件_第2张图片
为了给控件上的Image赋值。(其他控件赋值也是如此),需要添加一个属性
public String ImageUri { get; set; }

并且在Load事件给Image的Source赋值。
整个forecastInfo的后台代码:
public string ImageUri { get; set; }
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            BitmapImage bmp = new BitmapImage(new Uri(ImageUri, UriKind.Relative));
            WImg.Source = bmp;
        }


这样。用户控件就算了基本完成了。
接着。在Mainpage上添加这个控件。
首先,要在MainPage.xaml上添加命名空间
xmlns:my="clr-namespace:Wp7WhetherForecast"

这个命名空间的规则:namespace:后跟着的是工程名。我的工程就是Wp7WhetherForecast.所以如上。
然后添加控件:
<my:forecastInfo  x:Name="fore" HorizontalAlignment="Left" VerticalAlignment="Top"
                            Width="300" Height="100" Margin="0,0,0,0"  
                              ImageUri="/Wp7WhetherForecast;component/Images/sunday.jpg"/>

此前。我已经在工程中添加了一张图片。
<WP7>小试用户控件_第3张图片
而且图片的Building属性为Resource。
运行,成功!
<WP7>小试用户控件_第4张图片
PS:一开始没运行的时候,添加<forecastInfo的时候会提示不能找到,而且forecastInfo下面显示蓝色波浪线。但是智能提示显示是可以找到,这个问题不用紧张,保存运行就可以了。
如果要为用户控件上的其他控件赋值,可以和Image赋值一样操作即可。

你可能感兴趣的:(image,String,object,user,layout)